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
  • Validating and trapping errors

This chapter is an exciting one! Here’s where you tie the front end to the back end for the first time. You’ll remove the hardcoded data from the controllers, and eventually show data from the database in the browser instead. You’ll also 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 your grand plan.

Figure 7.1. This chapter focuses 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. You’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 you can add validation and why these different layers are useful.

Start by looking at how to call an API from an Express application.

7.1. How to call an API from Express

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

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

7.4. Adding data to the database via the API: add Loc8r reviews

7.5. Protecting data integrity with data validation

Summary

sitemap