Chapter 7. Consuming a REST API: Using an API from inside Express

 

This chapter covers

  • Calling an API from an Express application
  • Handling and using data returned by the API
  • Working with API response codes
  • Submitting data from the browser back to the API
  • Validation and error traps

This chapter is an exciting one! Here’s where we tie the front end to the back end for the first time. We’ll remove the hard-coded data from the controllers, and end up showing data from the database in the browser instead. On top of this we’ll push data back from the browser into the database via the API, creating new subdocuments.

The technology focus for this chapter is on Node and Express. Figure 7.1 shows where this chapter fits into the overall architecture and our grand plan.

Figure 7.1. This chapter will focus on updating the Express application from chapter 4 to interact with the REST API developed in chapter 6.

In this chapter we’ll discuss how to call an API from within Express, and how to deal with the responses. We’ll make calls to the API to read from the database and write to the database. Along the way we’ll look at handling errors, processing data, and creating reusable code by separating concerns. Toward the end we’ll cover the various layers of the architecture to which we can add validation, and why these different layers are useful.

We’ll start off by looking at how to call an API from the Express application.

7.1. How to call an API from Express

7.1.1. Adding the request module to our project

7.1.2. Setting up default options

7.1.3. Using the request module

7.2. Using lists of data from an API: The Loc8r homepage

7.2.1. Separating concerns: Moving the rendering into a named function

7.2.2. Building the API request

7.2.3. Using the API response data

7.2.4. Modifying data before displaying it: Fixing the distances

7.2.5. Catching errors returned by the API

7.3. Getting single documents from an API: The Loc8r Details page

7.3.1. Setting URLs and routes to access specific MongoDB documents

7.3.2. Separating concerns: Moving the rendering into a named function

7.3.3. Querying the API using a unique ID from a URL parameter