Node.js RESTful API
What is REST?
REST (Representational State Transfer) is a software architectural style proposed by Dr. Roy Fielding in his doctoral thesis in 2000.
Representational State Transfer is a set of architectural constraints and principles. Applications or designs that satisfy these constraints and principles are RESTful. Note that REST is a design style, not a standard. REST is typically based on the use of existing, widely popular protocols and standards such as HTTP, URI, XML (a subset of Standard Generalized Markup Language) and HTML (an application of Standard Generalized Markup Language). REST usually uses the JSON data format.
HTTP Methods
The following are the four methods of the basic REST architecture:GET- Used to retrieve data.
PUT- Used to update or add data.
DELETE- Used to delete data.
POST- Used to add data.
RESTful Web Services
A Web service is a platform-independent, loosely coupled, self-contained, programmable web-based application. It uses the open XML (a subset of Standard Generalized Markup Language) standard to describe, publish, discover, coordinate, and configure these applications, and is used to develop distributed, interoperable applications.
Web Services based on the REST architecture are RESTful.
Due to its lightweight nature and the ability to transfer data directly over HTTP, the RESTful approach to Web services has become the most common alternative. Clients can be implemented in various languages (such as Java programs, Perl, Ruby, Python, PHP, and Javascript [including Ajax]).
RESTful Web services can usually be accessed by automated clients or applications acting on behalf of users. However, the simplicity of such services allows users to interact with them directly, building a GET URL in their web browser and reading the returned content.
For more information, see:Detailed Explanation of RESTful Architecture
Creating RESTful
First, create a JSON data resource file 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:
| Serial No. | URI | HTTP method | Request content | Result |
|---|---|---|---|---|
| 1 | listUsers | GET | Empty | Display the list of all users |
| 2 | addUser | POST | JSON string | Add a new user |
| 3 | deleteUser | DELETE | JSON string | Delete user |
| 4 | :id | GET | Empty | Show detailed user information |
Get user list:
In the following code, we create a RESTful APIlistUsers, used 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("应用实例,访问地址为 http://%s:%s", host, port)
})
Next, run the following command:
$ node server.js 应用实例,访问地址为 http://0.0.0.0:8081
Visit http://127.0.0.1:8081/listUsers in the browser, and 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
In the following code, we create a RESTful APIaddUser, 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, run the following command:
$ node server.js 应用实例,访问地址为 http://0.0.0.0:8081
Visit http://127.0.0.1:8081/addUser in the browser, and 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 }
}
Show user details
In the following code, we create a RESTful API:id (user id), 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, run the following command:
$ node server.js 应用实例,访问地址为 http://0.0.0.0:8081
Visit http://127.0.0.1:8081/2 in the browser, and the result is as follows:
{
"name":"suresh",
"password":"password2",
"profession":"librarian",
"id":2
}
Delete user
In the following code, we create a RESTful APIdeleteUser, used to delete the detailed information of the specified user. In the following 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("应用实例,访问地址为 http://%s:%s", host, port)
})
Next, run the following command:
$ node server.js 应用实例,访问地址为 http://0.0.0.0:8081
Visit http://127.0.0.1:8081/deleteUser in the browser, and the result is as follows:
{ user1:
{ name: 'mahesh',
password: 'password1',
profession: 'teacher',
id: 1 },
user3:
{ name: 'ramesh',
password: 'password3',
profession: 'clerk',
id: 3 }
}
Other extensions