Table of content
- What is a router?
What is a route?
- A route or an endpoint is a unique path that works as an interface to our REST API layers (controller, services, and model/schema). Interfaces are made public. Frontend apps, devices, and other platforms can use interfaces to request data and operations.
- Let's take an analogy of a car. A car is a very complex mechanical machine. But all the complexity is hidden from us, the user. We use steering to steer the car's wheel, the gas pedal to speed up, the brake pedal to slow down, and so on. These are what we call interfaces. We don't need to know what goes behind those interfaces (leave that to mechanics).
- So all these layers we have created until now hide complexity and internal working from one another. They only provide service to other layers.
In your Node.js project, navigate to the
srcfolder and create a
routers.jsfile inside both the
The Node.js project structure will look something like this:
- We will use the express to create a router. Each router has an HTTP method.
- HTTP method takes in a string representing a unique path to our API and a controller method to handle the request-response cycle.
- Example: a client app sends a
getrequest to URL
https://localhost:5000/v1/api/authors. The URL string is parsed into different parts like protocol:
localhost:5000, and route:
/v1/api/authors. The string
/v1/apiis a prefix on all routes, so ignore it. The string
/authorswill check against the string provided to each router. The router with the
getmethod and string
/authorswill get a match and handles the incoming HTTP request.
- In the
./src/author/routers.jsfile put the below code.
We will repeat the same steps with
post routers. In the
./src/post/routers.js file put the below code.
Final code for server.js
- After creating all our layers and router for each use case, we can use them in our express app below.
Running REST API
- Finally, we can run our REST API app. Navigate to the root of our Node.js project and open a terminal.
- Run the command:
npm run serverto run the API app.
- Now we can test our API from the browser or use it directly in your frontend application. But the best and most manageable way is to use API test tools like Postman, ReadyAPI, and more.
- We have created routers for the
postand used them with our express app.
- In our next and final part, we will use Postman to test the working of our API.
- The link to the project repo is available here.