Node.js RESTful API

This section describes the .js of nodes in the world.

What is REST?

REST Chinese explained that expressive state transfer, or REST for short, is a software architecture style proposed by Dr. Roy Fielding in his 2000 doctoral thesis.

Expressive state transfer is a set of architectural constraints and principles. An application or design that meets these constraints and principles is RESTful.

It is important to note that REST is a design style, not a standard. R EST is typically based on existing, widely popular protocols and standards that use HTTP, URIs, and XML (a subset under the standard common tag language) and HTML (an application under the standard common tag language). REST usually uses the JSON data format.

HTTP method

Here are four methods of the REST basic architecture:
  • GET - Used to get 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-coupled, self-contained, programmable web-based application that can be described, published, discovered, coordinated, and configured using open XML (a subset of standard common markup language) standards for developing distributed interoperability applications.

RESTful is Web Services based on the REST architecture.

The RESTful approach to Web services has become the most common alternative due to lightweight and the nature of direct data transfer through HTTP. Clients can be implemented in a variety of languages, such as Java programs, Perl, Ruby, Python, PHP, and Javascript, including Ajax.

RESTful Web services are typically accessible through automated clients or applications that represent users. H owever, the simplicity of this service allows users to interact directly with it, use their Web browser to build a GET URL and read the returned content.

For more information, you can see: RESTful Architecture Details


Create RESTful

First, create a jason data resource file, user.json, 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:

Serial number Uri HTTP method Send content Results
1 listUsers GET Empty Displays a list of all users
2 addUser POST JSON string Add a new user
3 deleteUser DELETE JSON string Delete the user
4 :id GET Empty Show user details

Get a list of users:

The following code, we created the RESTful API listUsers, which reads the user's list of information, .js the server file code looks like this:

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, follow the following command:

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

The browser accesses the http://127.0.0.1:8081/listUsers results are 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 a user

If you want to add new user data, you can do this by creating the RESTful API addUser, .js file code looks like this:

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, follow the following command:

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

The browser accesses the http://127.0.0.1:8081/addUser results are 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 } 
}

Show user details

The following code, we created the RESTful API: id, which reads the details of the specified user, .js the server file code looks like this:

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, follow the following command:

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

The browser accesses the http://127.0.0.1:8081/2 results are as follows:

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

Delete the user

In the following code, we created the RESTful API deleteUser to remove the details of the specified user, in the following example, the user id is 2, 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, follow the following command:

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

The browser accesses the http://127.0.0.1:8081/deleteUser, and the results look like this:

{ user1:
   { name: 'mahesh',
     password: 'password1',
     profession: 'teacher',
     id: 1 },
  user3:
   { name: 'ramesh',
     password: 'password3',
     profession: 'clerk',
     id: 3 } 
}