Develop RESTful API using Node JS, Express JS

Develop RESTful API using Node JS, Express JS

Develop RESTful API 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.

Also Read:- Uploading files with ReactJS and NodeJS

Advantages:

  • Simple
  • Easy to use/implement
  • Easy to build
  • Uniform interface
  • The REST API is always independent of the type of platform or languages
  • 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:

  • Quick & easy development
  • High performance
  • Run on single thread to handle multiple concurrent requests
  • Easy to write API and interaction code
  • Streaming support
  • Monitoring possibilities
  • Authentication support
  • Lightweight, fast, and scalable

About 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. 
Few core features of Express framework −

  • 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.

Also Read:- Top 10 Companies Which Built their Apps with AngularJS and Node.js

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.

Note: The complete code reference can be downloaded from GitHub.

Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.

News & Blogs

f2030f8072e9f88d4678b2c8c256ea32.jpeg

The Top 10 Things Wrong with JavaScript

JavaScript has a reputation for being one of the worst programming language in existence, and for...

5c589c977403e60cd13285eba20ef5ca.jpeg

Top 10 Node.Js Frameworks to Use in 2020

Node.Js is a Javascript runtime environment and an open-source cross-platform. Javascript code is...

449d4afbbedaaf5c3f17ee0d225c7edb.png

A Simple CRUD App Using GraphQL, NodeJS, and Mo...

In my last article, I gave a global introduction to GraphQL. I compared it with REST, as the two ...