Latest web development tutorials

Node.js RESTful API

What is REST?

That REST Representational State Transfer (English: Representational State Transfer, called REST) ​​presented by Dr. Roy Fielding in his doctoral dissertation in 2000 to a style of software architecture.

Representational State Transfer is a set of architectural constraints and principles. Meet these constraints and principles of design or application is RESTful. Note that, REST is a style rather than the standard. REST is usually based on the use of HTTP, URI, and XML (a subset of the Standard Generalized Markup Language under) and HTML (an application under the Standard Generalized Markup Language) these existing widespread protocols and standards. REST typically use JSON data format.

HTTP method

The following four basic methods REST architecture:

  • GET - used to retrieve data.

  • PUT - used to add data.

  • DELETE - to delete data.

  • POST - used to update or add data.


RESTful Web Services

Web service is a platform-independent, loosely coupled, self-contained, programmable web-based applications, you can use Open XML (a subset of the Standard Generalized Markup Language under) standards to describe, publish, discover, coordination and configure these applications for the development of interoperable distributed applications.

REST-based Web Services architecture that is RESTful.

Due to the lightweight and direct transfer via HTTP characteristic data, RESTful Web service method has become the most common alternative. You can use a variety of languages ​​(such as Java programs, Perl, Ruby, Python, PHP and Javascript [including Ajax]) to achieve the client.

RESTful Web services can usually be accessed through automatic client or on behalf of the user's application. However, this simplicity allows service users to directly interact with them using their Web browser to build a GET URL and read the returns.

More reports, you can view: RESTful architecture Comments


Creating RESTful

First, create a json data resource file users.json, reads 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 created the following RESTful API:

No. URI HTTP method Send Content result
1 listUsers GET air Displays a list of all users
2 addUser POST JSON string Add a new user
3 deleteUser DELETE JSON string delete user
4 : Id GET air Display user details

Get a list of users:

The following code, we create aRESTful API listUsers, for reading user list information, 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)

})

Then execute the following command:

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

Access in the browser 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 user

The following code, we create aRESTful API addUser, used to add new user data, 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)

})

Then execute the following command:

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

Access in the browser 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 } 
}

Display user details

The following code, we create aRESTful API: id (user id),specify the details for the user to read, 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)

})

Then execute the following command:

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

Access in the browser http://127.0.0.1:8081/2, results are as follows:

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

delete user

The following code, we create aRESTful API deleteUser, detailed information for the specified user to delete 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)

})

Then execute the following command:

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

Access in the browser http://127.0.0.1:8081/deleteUser, results are as follows:

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