Easy Tutorial
❮ Nodejs Mongodb Nodejs Http Server ❯

Node.js RESTful API

What is REST?

REST, or Representational State Transfer, is a software architectural style introduced by Roy Fielding in his doctoral thesis in 2000. It is a set of constraints and principles that, when applied, result in a RESTful application or design. It is important to note that REST is a design style, not a standard. REST typically utilizes HTTP, URIs, XML (a subset of the Standard Generalized Markup Language), and HTML (an application of the Standard Generalized Markup Language) which are widely adopted protocols and standards. REST commonly uses JSON as the data format.

HTTP Methods


RESTful Web Services

A web service is a platform-independent, loosely coupled, self-contained, programmable web application that uses open XML standards to describe, publish, discover, coordinate, and configure these applications for developing distributed, interoperable applications.

Web services based on the REST architecture are known as RESTful web services.

Due to their lightweight nature and the ability to transmit data directly over HTTP, RESTful methods for web services have become one of the most common alternatives. Clients can be implemented in various languages such as Java, Perl, Ruby, Python, PHP, and JavaScript (including Ajax).

RESTful web services can typically be accessed through automatic clients or applications acting on behalf of users. However, the simplicity of these services allows users to interact directly with them by building a GET URL in their web browser and reading the returned content.

For more details, see: Detailed Explanation of RESTful Architecture


Creating RESTful

First, create a JSON data resource file named users.json with the following content:

{
   "user1" : {
      "name" : "mahesh",
      "password" : "password1",
      "profession" : "teacher",
      "id": 1
   },
   "user2" : {
      "name" : "suresh",
      "password" : "password2",
      "profession" : "librarian",
      "id": 2
   },
   "user3" : {
      "name" : "ramesh",
      "password" : "password3",
      "profession" : "clerk",
      "id": 3
   }
}

Based on the above data, we create the following RESTful APIs:

No. URI HTTP Method Sent Content Result
1 listUsers GET Empty Display list of all users
2 addUser POST JSON String Add new user
3 deleteUser DELETE JSON String Delete user
4 :id GET Empty Display user details

Retrieving User List:

The following code creates the RESTful API listUsers to read the list of user information. The server.js file code is as follows:

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 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)
})
console.log("Application instance, access address is http://%s:%s", host, port)

Next, execute the following command:

$ node server.js 
Application instance, access address is http://0.0.0.0:8081

Visit http://127.0.0.1:8081/listUsers in your browser, and the result will be as follows:

{
   "user1" : {
      "name" : "mahesh",
      "password" : "password1",
      "profession" : "teacher",
      "id": 1
   },
   "user2" : {
      "name" : "suresh",
      "password" : "password2",
      "profession" : "librarian",
      "id": 2
   },
   "user3" : {
      "name" : "ramesh",
      "password" : "password3",
      "profession" : "clerk",
      "id": 3
   }
}

Add User

The following code creates a RESTful API addUser to add new user data. The server.js file code is as follows:

var express = require('express');
var app = express();
var fs = require("fs");

// New user data to be added
var user = {
   "user4" : {
      "name" : "mohit",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}

app.get('/addUser', function (req, res) {
   // Read existing data
   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));
   });
})

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port
  console.log("Application instance, access address is http://%s:%s", host, port)

})

Next, execute the following command:

$ node server.js 
Application instance, access address is http://0.0.0.0:8081

Visit http://127.0.0.1:8081/addUser in your browser, and the result will be as follows:

{ user1:
   { name: 'mahesh',
     password: 'password1',
     profession: 'teacher',
     id: 1 },
  user2:
   { name: 'suresh',
     password: 'password2',
     profession: 'librarian',
     id: 2 },
  user3:
   { name: 'ramesh',
     password: 'password3',
     profession: 'clerk',
     id: 3 },
  user4:
   { name: 'mohit',
     password: 'password4',
     profession: 'teacher',
     id: 4 } 
}

Display User Details

The following code creates a RESTful API :id (user id) to read the detailed information of a specified user. The server.js file code is as follows:

var express = require('express');
var app = express();
var fs = require("fs");

app.get('/:id', function (req, res) {
   // First, read existing users
fs.readFile(__dirname + "/" + "users.json", 'utf8', function (err, data) {
    data = JSON.parse(data);
    var user = data["user" + req.params.id];
    console.log(user);
    res.end(JSON.stringify(user));
});
})

var server = app.listen(8081, function () {

  var host = server.address().address;
  var port = server.address().port;
  console.log("Application instance, access address is http://%s:%s", host, port);

})

Next, execute the following command:

$ node server.js 
Application instance, access address is http://0.0.0.0:8081

Visit http://127.0.0.1:8081/2 in the browser, the result is as follows:

{
   "name":"suresh",
   "password":"password2",
   "profession":"librarian",
   "id":2
}

Delete User

The following code creates the RESTful API deleteUser to delete the details of a specified user. In this example, the user id is 2. The server.js file code is as follows:

var express = require('express');
var app = express();
var fs = require("fs");

var id = 2;

app.get('/deleteUser', function (req, res) {

   // First read existing users.
   fs.readFile(__dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse(data);
       delete data["user" + id];

       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("Application instance, access address is http://%s:%s", host, port);

})

Next, execute the following command:

$ node server.js 
Application instance, access address is http://0.0.0.0:8081

Visit http://127.0.0.1:8081/deleteUser in the browser, the result is as follows:

{
  "user1": {
    "name": "mahesh",
    "password": "password1",
    "profession": "teacher",
    "id": 1
  },
  "user3": {
    "name": "ramesh",
    "password": "password3",
    "profession": "clerk",
    "id": 3
  }
}
❮ Nodejs Mongodb Nodejs Http Server ❯