Build a RESTful API with Express
Build a simplified Express API.
We'll cover the following...
Overview
Let’s implement a simplified Express API that serves recipe data via JSON over HTTP. We’ll call it Express Recipes. The request-response cycle below traces how a user’s GET
request would flow through the Express Recipes application.
To keep the API code organization easy to understand, maintain and modify, we’ll structure and write modular code using three main layers, namely the router
, controller
, and service
.
- The
router
for a given resource is responsible for routing requests to the appropriatecontroller
based on the URL. - The
controller
for a given resource defines the logic for handling each route and is responsible for manipulating the state of a resource in the API. They also send back a response (either successful or not) to the client. - The
service
encapsulates or groups together the functions that perform a specific category of tasks in an application, like making CRUD transactions for a given resource. Services make code DRY (don’t repeat yourself principle) because the functions defined in aservice
can be reused throughout the application.
Overall, structuring and layering of the code this way would lead to better modularization, encapsulation, and separation of concerns in the codebase.
Here are the steps involved in the request-response cycle:
- The browser sends a
GET
request for all the