Instagram
youtube
Facebook
Twitter

Express.js Restful API

ExpressJS- Restful API

  • API stands for Application Programming Interface.
  • APIs are mechanisms that enable two software components to communicate with each other using a set of definitions and protocols.
  • REST here stands for Representational Transfer state.

Let us create API using Express. Install the cookie parser using Command:

npm install cookie-parser

In app.js

var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var cookieParser = require('cookie-parser')

var app = express();

app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(upload.array());

//Require the Router we defined in movies.js
var movies = require('./books.js');

//Use the Router on the sub route /movies
app.use('/books', movies);

app.listen(3000);

In books.js, All the crud operations including GET, POST, PUT, and DELETE in the below code.

var express = require('express');
var router = express.Router();
var books = [
   {id: 101, name: "Words of Radiance",Author:"Brandon Sanderson", year: 2014, rating: 4.75},
   {id: 102, name: "Harry Potter and the Deathly Hallows",Author:"J.K.Rowling", year: 2007, rating: 4.62},
   {id: 103, name: "Becoming",Author:"Michelle Obama", year: 2018, rating: 4.49},
   {id: 104, name: "The Help",Author:"Kathryn Stockett", year: 2009, rating: 4.47},
];

// fetch the data using ID using get http method
router.get('/:id([0-9]{3,})', function(req, res){
   var currbook = books.filter(function(book){
      if(book.id == req.params.id){
         return true;
      }
   });
   
   if(currbook.length == 1){
      res.json(currbook[0])
   } else {
      res.status(404);  //Set status to 404 as book was not found
      res.json({message: "Not Found"});
   }
});

// Adding details of book using POST
router.post('/', function(req, res){
   //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.Author.toString().match(/^[0-9]\.[0-9]$/g)||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g)){
      res.status(400);
      res.json({message: "Bad Request"});
   } else {
      var newId = books[books.length-1].id+1;
      books.push({
         id: newId,
         name: req.body.name,
         Author:req.body,author,
         year: req.body.year,
         rating: req.body.rating
      });
      res.json({message: "New book created.", location: "/books/" + newId});
   }
});

// Editing details using PUT method
router.put('/:id', function(req, res) {
   //Check if all fields are provided and are valid:
   if(!req.body.name ||
      !req.body.year.toString().match(/^[0-9]{4}$/g) ||
      !req.body.rating.toString().match(/^[0-9]\.[0-9]$/g) ||
      !req.params.id.toString().match(/^[0-9]{3,}$/g)){
      res.status(400);
      res.json({message: "Bad Request"});
   } else {
      //Gets us the index of book with given id.
      var updateIndex = books.map(function(book){
         return book.id;
      }).indexOf(parseInt(req.params.id));
      
      if(updateIndex === -1){
         //book not found, create new
         books.push({
            id: req.params.id,
            name: req.body.name,
            Author:req.body.author,
            year: req.body.year,
            rating: req.body.rating
         });
         res.json({
            message: "New book created.", location: "/books/" + req.params.id});
      } else {
         //Update existing book
         books[updateIndex] = {
            id: req.params.id,
            name: req.body.name,
            Author:req.body.author,
            year: req.body.year,
            rating: req.body.rating
         };
         res.json({message: "book id " + req.params.id + " updated.",
            location: "/books/" + req.params.id});
      }
   }
});

// Deleting Details of books using Id
router.delete('/:id', function(req, res){
   var removeIndex = books.map(function(book){
      return book.id;
   }).indexOf(req.params.id); //Gets us the index of book with given id.
   
   if(removeIndex === -1){
      res.json({message: "Not found"});
   } else {
      books.splice(removeIndex, 1);
      res.send({message: "book id " + req.params.id + " removed."});
   }
});
module.exports = router;

 Run the server using the command:

node app.js

We will check whether our APIs work properly or not using Postman. Postman is an API platform for building and using APIs. Download Postman using the link: https://www.postman.com/downloads/

  • Verifying GET method API using Postman