Create REST API with Node and Express - Part 5

We are creating a REST API for a simple blog post that will serve blog posts and author information.

author profile image
Sakchhyam G
@saksham
Create REST API with Node and Express - Part 5

Table of content

  1. What is a router?
  2. Code
  3. Summary

What is a route?

  • A route or an endpoint is a unique path that works as an interface to our 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.

Code

  • Navigate to the src folder and create a routers.js file inside both the author and the post folder.

  • The project structure will look something like this:

    1src/ 2├─ author/ 3│ ├─ schema.js 4│ ├─ services.js 5│ ├─ controllers.js 6│ ├─ routers.js 7├─ post/ 8│ ├─ schema.js 9│ ├─ services.js 10│ ├─ controllers.js 11│ ├─ routers.js 12├─ config.js 13.env 14package.json 15server.js

author routers

  • 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 get request to URLhttps://localhost:5000/v1/api/authors. The URL string is parsed into different parts like protocol:https, hostname:localhost:5000, and route: /v1/api/authors. The string /v1/api is a prefix on all routes, so ignore it. The string /authors will check against the string provided to each router. The router with the get method and string /authors will get a match and handles the incoming HTTP request.
1const express = require("express"); 2const router = express.Router(); 3const AuthorControllers = require("./controllers"); 4 5router.post("/authors", AuthorControllers.createAuthor); 6// Below ":id" indicates a URL parameter. 7// Eg: a request is sent with the following URL: `https://localhost:5000/v1/api/authors/60465952ed6770392c038261` 8// then id "60465952ed6770392c038261" can be extracted from request object as req.params.id 9router.get("/authors/:id", AuthorControllers.getAuthorById); 10router.get("/authors", AuthorControllers.getAllAuthor); 11 12module.exports = router;

post routers

We will repeat the same steps with post routers.

1const express = require("express"); 2const router = express.Router(); 3const PostControllers = require("./controllers"); 4 5router.post("/posts", PostControllers.createPost); 6router.get("/posts/:id", PostControllers.getPostById); 7router.get("/posts", PostControllers.getAllPost); 8router.put("/posts/:id", PostControllers.updatePostById); 9 10module.exports = router;

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.
1const express = require("express"); 2 3const config = require("./src/config"); 4const connectDB = require("./src/connectDB"); 5// importing routers for author 6const AuthorRouters = require("./src/author/routers"); 7// importing routers for post 8const PostRouters = require("./src/post/routers"); 9 10const app = express(); 11// prefix for all routers indicating API version 12const apiVersion = "/api/v1"; 13connectDB(); 14 15app.use(express.json()); 16app.use(express.urlencoded({ extended: false })); 17 18// using/exposing routers along with prefix 19app.use(apiVersion, AuthorRouters); 20app.use(apiVersion, PostRouters); 21 22app.listen(config.port, () => { 23 console.log(`Server running at PORT:${config.port}`); 24});

Running API

  • Finally, we can run our API app. Navigate to the root of our project and open a terminal.
  • Run the command: npm run server to 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.

Summary

  • We have created routers for the author and the post and 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.
Advertisement
Advertisement