Node.js RESTful API
What is REST?
REST, short for Representational State Transfer, is a software architectural style introduced by Dr. Roy Fielding in his 2000 doctoral dissertation.
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 existing, widely used 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 basic methods of REST:
-
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 application that uses open XML (a subset of Standard Generalized Markup Language) standards to describe, publish, discover, coordinate, and configure these applications, for developing distributed, interoperable applications.
Web services based on the REST architecture are RESTful.
Due to their 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 a variety of languages, such as Java, Perl, Ruby, Python, PHP, and JavaScript (including Ajax).
RESTful web services are usually accessible through automated clients or applications acting on behalf of users. However, the simplicity of such services allows users to interact with them directly, using their web browser to construct a GET URL and read the returned content.
For more information, see:RESTful architecture explained
Create a 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 methods | Send content | Result |
|---|---|---|---|---|
| 1 | listUsers | GET | null | 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 | null | Display user details |
Get the user list:
In the following code, we create a RESTful API listUsersfor reading the list of user information; the server.js file code is shown below:
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
Visit 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 a user
In the following code, we create a RESTful API addUserUsed to add new user data; the server.js file code is shown below:
var express = require('express');
var app = express();
var fs = require("fs");
//New user data 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("应用实例,访问地址为 http://%s:%s", host, port)
})
Next, execute the following command:
$ node server.js
应用实例,访问地址为 http://0.0.0.0:8081
Visit 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
In the following code, we create a RESTful API :id (user id)Used to read the details of a specified user; the server.js file code is shown below:
var express = require('express');
var app = express();
var fs = require("fs");
app.get('/:id', function (req, res) {
// First we read the 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("应用实例,访问地址为 http://%s:%s", host, port)
})
Next, execute the following command:
$ node server.js
应用实例,访问地址为 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
In the following code, we create a RESTful API deleteUserUsed to delete the details of a specified user; in this example the user id is 2. The server.js file code is shown below:
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, execute the following command:
$ node server.js
应用实例,访问地址为 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 }
}