English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer & URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

Other NodeJS

Node.js RESTful API

What is REST?

REST, which stands for Representational State Transfer (English: Representational State Transfer, abbreviated as REST), was proposed by Dr. Roy Fielding in2a software architecture style proposed in his doctoral dissertation in 000.

Representational State Transfer (REST) is a set of architectural constraints and principles. Applications or designs that meet these constraints and principles are considered RESTful. It should be noted that REST is a design style rather than a standard. REST is typically based on the use of HTTP, URI, and XML (a subset of the Standard Generalized Markup Language) as well as HTML (an application of the Standard Generalized Markup Language), these widely used existing protocols and standards. REST usually uses JSON data format.

HTTP method

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 application that can be described, published, discovered, coordinated, and configured using the open XML (a subset of the Standard Generalized Markup Language) standard, for the development of distributed interoperable applications.

Web services based on the REST architecture are known as RESTful.

Due to their lightweight nature and the ability to transmit data directly over HTTP, the RESTful method for 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 are typically accessed through an automatic client or an application representing the user. However, the simplicity of this service allows users to interact with it directly, using their web browsers to construct a GET URL and read the returned content.

Create RESTful

Firstly, create a json data resource file users.json, the content is as follows:

{
   "user1" : {
      "name" : "Sea",
      "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:

NumberURIHTTP methodContent sentResult
1listUsersGETEmptyDisplay all user list
2addUserPOSTJSON stringAdd new user
3deleteUserDELETEJSON stringDelete User
4:idGETEmptyDisplay user detailed information

Get user list:

In the following code, we have created a RESTful API listUsersto read the information list of users, the code in server.js 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("Application Example, access address is http://%s:%s", host, port)
}

Next, execute the following command:

$ node server.js 
Application Example, access address is http://0.0.0.0:8081

Access http: in the browser//127.0.0.1:8081/listUsers, the result is as follows:

{
   "user1" : {
      "name" : "Sea",
      "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 have created a RESTful API addUserto add new user data, the code in server.js is as follows:

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) {
   // Reading 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("Application Example, access address is http://%s:%s", host, port)
}

Next, execute the following command:

$ node server.js 
Application Example, access address is http://0.0.0.0:8081

Access http: in the browser//127.0.0.1:8081/addUser, the result is as follows:

{ user1:
   { name: 'Sea',
     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 have created a RESTful API :id (user ID)to read the detailed information of a specified user, the code in server.js is as follows:

var express = require('express');
var app = express();
var fs = require("fs");
app.get('/:id', function(req, res) {
   // Firstly, 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("Application Example, access address is http://%s:%s", host, port)
}

Next, execute the following command:

$ node server.js 
Application Example, access address is http://0.0.0.0:8081

Access http: in the browser//127.0.0.1:8081/2The result is as follows:

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

Delete User

In the following code, we have created a RESTful API deleteUser, Used to delete the detailed information of the specified user, in the following example, the user id is 2, the code of server.js file 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("Application Example, access address is http://%s:%s", host, port)
}

Next, execute the following command:

$ node server.js 
Application Example, access address is http://0.0.0.0:8081

Access http: in the browser//127.0.0.1:8081/deleteUser, the result is as follows:

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