Back End

Build REST API with Node.JS & Express

An API is an application programming interface. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server side and allows the client to interact with.
REST determines how the API looks like. It stands for “Representational State Transfer”. It is an artichectural style that defines set of rules which developers follow in order to create Web Service.

In this tutoriel, we will learn how to create a RESTful API with CRUD operations in node.js using Express framework, it is essential to have basic knowledge of javascript.

Getting Started

We will need to use some tools :

Before get started if you have not already Node.js environement installed on your machine, try to download and install the most stable version from don’t install last version since it may contain bugs and features that could be removed from the final version.
To ensure that your environemnt is well set up on your machine try out the two below commands in cmd instance :

 >   node   -v
 >   npm   -v

Initiailizing the App

Create folder named node-api, in the root of this one run npm init :

 >   mkdir   node-api
 >   cd   node-api

 >   npm   init

Once finished it will create package.json file in the root of your project which contains a set of properties (name app, version, description, dependencies…) 


install express through the below  command 

 >   npm  install  express  –save

Create app.js file

app.js is the entry point of our server application let’s create it  (should be in the root app with package.json) 
Edit the app.js file with the following content :

const express = require('express');
const app = express();

//index route
app.get("/", (req, res) => {
res.json("welcome to node.js api")

//listen requests
app.listen(4000, () => {    
console.log("server up through port 4000");

run the server and access the endpoint defined.

 >   node app.js

we’ll get “server up through port 4000” in the console.
Checkout on the web browser

Create router.js file

let’s customize the routes (endpoints) of our api in router.js file which will subsequently be included in the app.js file. the project structure looks like

            |____ node_modules                
            |____ route                                    
                                |____ router.js        
            |____ app.js                
            |____ package.json

Retrieve books [GET:books]

As it was already discussed we will end up with CRUD operations. After creating router.js file inside route folder we will define the routes as shown, starting with GET retrieving method

const express = require(“express“);
const router = express.Router();

//customizing response
const customResponse = (status, msg, result) => {
          let response = {
                       “ok”: status,
                       “message”: msg,
          return response;

//index route
router.get(“/”, (req, res) => {
             res.json(customResponse(true“welcome to node.js api”));

//list of books
let books = [
           id: 1, 
           title: “Computer Architecture”, 
           category: “computer science”, 
           id: 2, 
           title: “Become Rockstart JavaScript Developer”, 
           category: “programming”, 
           price: 150
           id: 3,
           title: “Monolith to Microservices”, 
           category: “software engineering”, 
           price: 200
           id: 4, 
           title: “Modern Full-Stack Development”, 
           category:  “programming”, 
           price: 120

//get books endpoint 
router.get(“/api/books”, (req, res) => {
             res.json(customResponse(true, “success”, books));
module.exports = router;

As shown above we have created simple route that returns a set of books and moved there the first route created in app.js
we have also customized the return response by a specific model which contains the status of the response (ok property which takes the value true or false depending on), a custom message and result object which will contain the response data of requested resource.
After exporting the custom router now let’s include it in the app :

const express = require(‘express‘);
const app = express();
const router = require(‘./route/router‘);

//include custom router

//listen requests
app.listen(4000, () => {   
        console.log(“server up through port 4000”);

Once done move to postman in order to checkout the endpoint on :

get method

Create new Book [POST:book]

With the post method we will create new book in the dataset.
Firstly in order to handle the objects sent by user in the http body request we have to use body-parser dependence, let’s install through npm

 >   npm install –save  body-parser

 we have to include the usage of body-parser in app.js

const express = require(‘express‘);
const app = express();
const bodyParser = require(‘body-parser‘);
const router = require(‘./route/router‘);

//parse body request to json


//include custom router


//listen requests

app.listen(4000, () => {    
        console.log(“server up through port 4000”);

turning back to the router.js and define the post route : 

//post new book“/api/addBook”, (req, res) => {
        const book = req.body;
        console.log(“> new book has been created with id : “ + book._id);
        res.json(customResponse(true“new book created with success”, book);
module.exports = router;

Testing the route on postman  with POST qualifier method, in body section select raw with JSON option and put the object there as the below :

post method

Once done turn back to we found the created object was added to the set.

Update a Book [PUT:book]

In update route we will change some attributes of a given object based on the _id

//update book
router.put(“/api/updateBook”, (req, res) => {
   const book = books.find((object, index) => {
         if(object._id === req.body._id){
                     books[index] = req.body;
                     return req.body;
    book ?
            res.json(customResponse(true,“book updated with success”, req.body)) :

            res.json(customResponse(false, “book with id : “+req.body._id + ” doesn’t exist”));

Checkout  with PUT qualifier method, let’s modify the properties of the book  _id : 3 

If we introduce an id object which is not included in the list we’ll get custom message in generic response that this book doesn’t exist.

Delete a Book [DELETE:book]

In delete endpoint the method implmentation is done as shown :

//delete book
router.delete(“/api/deleteBook”, (req, res) => {
       const book = books.find((object) => {
             if(object._id == req.query._id){
                        books = books.filter(object => object._id != req.query._id);
                        return req.query._id;
       book ?
            res.json(customResponse(true, “book with _id : “+ book._id +” has been deleted with success”)) :
            res.json(customResponse(false, “book with id : ” + req.query._id +doesn’t exist”));

deleting book specifying the _id in request param 

delete method

Returning to we found the object _id 2 has been removed from the set.

That was simple and fast method for exposing the crud operations as REST, otherwise we can customize lot of aspects for best practise for ex put the crud methods aside in standlone controller and grant the router only for endpoints declarations

const express = require(“express“);
const bookController = require(“../controller/bookController“);
const router = express.Router();

//entry endpoint
router.get(“/”, bookController.indexRoute);

//get books 
router.get(“/api/books”, bookController.getBooks);

//post new book“/api/addBook”, bookController.createBook);

//update book
router.put(“/api/updateBook”, bookController.updateBook);

//delete book
router.delete(“/api/deleteBook”, bookController.deleteBook);

module.exports = router;


In this passage we learned how to build REST api using node.js and express framework. The code is available here in github repository, any questions please leave them in comments section.

Thank you for reading, see you in next tutos.

Comment here