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

 

This chapter covers

  • Examining the rules of REST APIs
  • Evaluating API patterns
  • Handling typical CRUD functions (create, read, update, delete)
  • Using Express and Mongoose to interact with MongoDB
  • Testing API endpoints

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

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

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

You’ll start 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. When you have that knowledge under your belt, you’ll move on to building your API for Loc8r, covering all the typical CRUD operations. We’ll discuss Mongoose along the way and get into some Node programming and more Express routing.

6.1. The rules of a REST API

6.2. Setting up the API in Express

6.3. GET methods: Reading data from MongoDB

6.4. POST methods: Adding data to MongoDB

6.5. PUT methods: Updating data in MongoDB

6.6. DELETE method: Deleting data from MongoDB

Summary

sitemap