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 do not already have Node.js environment installed on your machine, try to download and install the most stable version from https://nodejs.org don’t install last version since it may contain bugs and features that could be removed from the final version.
To ensure that your environment 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 location, 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…) 

package.json

install express through npm 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 http://127.0.0.1:4000/ on the web browser

Create router.js file

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

 node-api                
            |____ 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,
                       result
          }
          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”, 
           price:100
       },
       {
           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 a simple route that returns a set of books, then 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
app.use(router);

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

Once done, jump to postman in order to checkout the endpoint, http://127.0.0.1:4000/api/books :

get method

Create new Book [POST:book]

With the post method we will create a 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 dependency, let’s install it

 >   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

app.use(bodyParser.json());

//include custom router

app.use(router);

//listen requests

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

turning back to the router.js, defining the endpoint route : 

//post new book
router.post(“/api/addBook”, (req, res) => {
        const book = req.body;
        books.push(book);
        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 http://127.0.0.1:4000/api/addBook on postman  with POST qualifier method, in body section select raw with JSON option and put the object there as shown :

post method

Once done turn back to http://127.0.0.1:4000/api/books we will find the created object has been pushed to the set.

Update a Book [PUT:book]

In the edit 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 http://127.0.0.1:4000/api/updateBook 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 the request param http://127.0.0.1:4000/api/deleteBook?_id=2 

delete method

Returning to http://127.0.0.1:4000/api/books 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, putting the crud methods aside in a standalone 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
router.post(“/api/addBook”, bookController.createBook);

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

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

module.exports = router;

Conclusion

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.

Comments

You must be Login in to post a comment.

Related Posts