Node.js RESTful API


What is REST?

REST is a software architecture style proposed by Dr. Roy Fielding in his doctoral thesis in 2000.

Representational state transfer is a set of architectural constraints and principles. An application or design that satisfies these constraints and principles is RESTful. It is important to note that REST is a design style and not a standard. REST is typically based on existing widely popular protocols and standards using HTTP, URIs, and XML (a subset of Standard Generalized Markup Language) and HTML (an application of Standard Generalized Markup Language). REST typically uses the JSON data format.

HTTP methods

The following are the four methods of the REST basic architecture:


  • GET - used to obtain data.

  • PUT - Used to add data.

  • DELETE - Used to delete data.

  • #POST - Used to update or add data.


RESTful Web Services

Web service is a platform-independent, low-coupling, self-contained, programmable web-based application that can Use open XML (a subset of Standard Generalized Markup Language) standards to describe, publish, discover, coordinate and configure these applications for the development of distributed, interoperable applications.

Web Services based on REST architecture are RESTful.

The RESTful approach to web services has become the most common alternative due to its lightweight nature and the ability to transfer data directly over HTTP. Clients can be implemented using a variety of languages, such as Javascript, Perl, Ruby, Python, PHP, and Javascript [including Ajax].

RESTful Web services are typically accessible through automated clients or applications on behalf of users. However, the simplicity of this service allows users to interact with it directly, using their web browser to construct a GET URL and read the returned content.

For more introduction, you can view: RESTful architecture detailed explanation


Create RESTful

First, create a json data resource file users.json , the content is 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
   }
}

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

##2addUserPOSTJSON stringAdd new user3deleteUserDELETEJSON stringDelete user 4:idGETemptyDisplay user details

Get the user list:

With the following code, we created a RESTful API listUsers, which is used to read the user's information list. 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("应用实例,访问地址为 http://%s:%s", host, port)

})

Next execute the following command:

$ node server.js 
应用实例,访问地址为 http://0.0.0.0:8081

Access http://127.0.0.1:8081/listUsers in the browser, the result is 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

With the following code, we created a RESTful API addUser, which is used to add new user data. The server.js file code is as follows:

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

//添加的新用户数据
var user = {
   "user4" : {
      "name" : "mohit",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}

app.get('/addUser', function (req, res) {
   // 读取已存在的数据
   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("应用实例,访问地址为 http://%s:%s", host, port)

})

Next execute the following command:

$ node server.js 
应用实例,访问地址为 http://0.0.0.0:8081

Access http://127.0.0.1:8081/addUser in the browser, the result is 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, we create The RESTful API :id (user id) is used to read the detailed information of the 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) {
   // 首先我们读取已存在的用户
   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("应用实例,访问地址为 http://%s:%s", host, port)

})

Next execute the following command:

$ node server.js 
应用实例,访问地址为 http://0.0.0.0:8081

Access 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

With the following code, we created a RESTful API deleteUser, used to delete the detailed information of the specified user. In the following example, the user id is 2, and 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" + 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("应用实例,访问地址为 http://%s:%s", host, port)

})

Next execute the following command:

$ node server.js 
应用实例,访问地址为 http://0.0.0.0:8081

Access 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 } 
}
Serial numberURI HTTP methodSend contentResult
1listUsersGET EmptyDisplay all user list