Develop RESTful APIs using Node JS, Express JS

Develop RESTful APIs using Node JS, Express JS

REST (Representational State Transfer) is web standards based architecture and uses HTTP Protocol. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. REST uses various representations to represent a resource like text, JSON, and XML but JSON is the most popular one.

Why do we need RESTful Web Services?
REST is an architecture style for designing networked applications. REST is a lightweight alternative to mechanisms like RPC (Remote Procedure Calls) and Web Services (SOAP, WSDL, et al.). The World Wide Web itself, based on HTTP, can be viewed as an REST-based architecture. The entire modern web browsers are REST client. RESTful applications use HTTP methods (GET, POST, PUT, and DELETE) to perform CRUD operations.

Advantages:

  1. Simple
  2. Easy to use/implement
  3. Easy to build
  4. Uniform interface
  5. The REST API is always independent of the type of platform or languages
  6. Visible, reliable, and scalable

Why opt Node JS for building RESTful APIS?
Node.js is a powerful JavaScript framework built on Google Chrome’s JavaScript V8 Engine. It is used to develop I/O intensive web applications like video streaming sites, single-page applications, etc. Node.js development is open source and used by thousands of web developers around the world.

Advantages:

  1. Quick & easy development
  2. High performance
  3. Run on single thread to handle multiple concurrent requests
  4. Easy to write API and interaction code
  5. Streaming support
  6. Monitoring possibilities
  7. Authentication support
  8. Lightweight, fast, and scalable

Express JS:
Express is a flexible Node.js web application framework that provides a robust set of features to develop mobile and web applications. It facilitates the rapid development of Node based Web applications.

  • Allows setting up of middleware to respond to HTTP Requests.
  • Defines a routing table which is used to perform different actions based on HTTP Method and URL.
  • Allows to the dynamic rendering of HTML Pages based on passing arguments to templates.

Step 1: Create a package.json file.

{
  "name": "restapi",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "cookie-parser": "^1.4.3",
    "express": "^4.16.3",
    "multer": "^1.3.1"
  }
}

Note: The package.json file can be created by using npm init command (recommended way).

Step 2: Create server.js file.

var express = require('express');
var app = express();
var fs = require("fs");
app.get('/listUsers', function (req, res) {
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       console.log( data );
       res.end( data );
   });
})
var user = {
   "user4" : {
      "name" : "lokesh",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}
app.post('/addUser', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       data["user4"] = user["user4"];
       console.log( data );
       res.end( JSON.stringify(data));
   });
})
app.get('/:id', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
      var users = JSON.parse( data );
      var user = users["user" + req.params.id] 
      console.log( user );
      res.end( JSON.stringify(user));
   });
})
var id = 2;
app.delete('/deleteUser', function (req, res) {
// First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       delete data["user" + 2];
       
       console.log( data );
       res.end( JSON.stringify(data));
   });
})
var server = app.listen(8081, function () {
var host = server.address().address
  var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})

Note: You can add multiple routes based on your requirement.

Step 3: Open CMD, execute npm install command.

Step 4: After successful installation of node modules, run below command into CMD.

node server.js

The node server will start running into port number 8081 with corresponding API Routes; you can point to the below URL to test the application.

http://localhost:8081

Step 5: Testing REST APIs

We can use any of the REST Clients like Postman Chrome App or through any of the Programming languages like Java, C#, PHP, etc., to consume the APIs.

Other Blog Posts

All That You Need To Know: Front End, Backend, Full Stack

All That You Need To Know: Front End, Backend, Full Stack

With time people have evolved themselves a lot and adapted the recent technologies so quickly that they are keen to know the insights about them. It is crucial to cherry-pick laudable developers ir...

read more
9 Web development trends you simply cannot ignore

9 Web development trends you simply cannot ignore

Catching your intended interest group's eye wouldn't cut it any longer. With rivalry getting to be stiffer with each passing day, you must keep them intrigued for quite some time as every o...

read more
Why create an e-commerce website with Node.JS as backend and HTML5 as frontend platform?

Why create an e-commerce website with Node.JS as backend and HTML5 as frontend platform?

While Node.js is by no means perfect, its ability to support thousands of concurrent connections on a single thread is an incredible asset to developers creating programs with high data transaction...

read more