Chapter 6. Writing a REST API: Exposing the MongoDB database to the application

 

This chapter covers

  • Rules of REST APIs
  • API patterns
  • Typical CRUD functions (create, read, update, delete)
  • Using Express and Mongoose to interact with MongoDB
  • Testing API endpoints

As we come in to this chapter we have a MongoDB database set up, but we can only interact with it through the MongoDB shell. During this chapter we’ll build a REST API so that we can interact with our database through HTTP calls and perform the common CRUD functions: create, read, update, and delete.

We’ll mainly be working with Node and Express, using Mongoose to help with the interactions. Figure 6.1 shows where this chapter fits into the overall architecture.

Figure 6.1. This chapter will focus on building the API that will interact with the database, exposing an interface for the applications to talk to.

We’ll start off by looking at the rules of a REST API. We’ll discuss the importance of defining the URL structure properly, the different request methods (GET, POST, PUT, and DELETE) that should be used for different actions, and how an API should respond with data and an appropriate HTTP status code. Once we have that knowledge under our belts we’ll move on to building our API for Loc8r, covering all of the typical CRUD operations. As we go, we’ll discuss a lot about Mongoose, and get into some Node programming and more Express routing.


6.1. The rules of a REST API

6.1.1. Request URLs

6.1.2. Request methods

6.1.3. Responses and status codes

6.2. Setting up the API in Express

6.2.1. Creating the routes

6.2.2. Creating the controller placeholders

6.2.3. Including the model

6.2.4. Testing the API

6.3. GET methods: Reading data from MongoDB

6.3.1. Finding a single document in MongoDB using Mongoose

6.3.2. Finding a single subdocument based on IDs

6.3.3. Finding multiple documents with geospatial queries

6.4. POST methods: Adding data to MongoDB