YouTip LogoYouTip

Nodejs Restful Api

What is REST?

\\n\\nREST, or Representational State Transfer, is a software architectural style proposed by Dr. Roy Fielding in his 2000 doctoral dissertation.\\n\\nRepresentational State Transfer is a set of architectural constraints and principles. An application or design that satisfies these constraints and principles is RESTful. It is important to 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, and XML (a subset of the Standard Generalized Markup Language) as well as HTML (an application of the Standard Generalized Markup Language). REST typically uses the JSON data format.\\n\\n

HTTP Methods

\\n\\nThe following are the four methods of the basic REST architecture:\\n\\n* GET - Used to retrieve data.\\n\\n* PUT - Used to update or add data.\\n\\n* DELETE - Used to delete data.\\n\\n* POST - Used to add data.\\n\\n
\\n\\n

RESTful Web Services

\\n\\nA Web service is a platform-independent, loosely coupled, self-contained, programmable web-based application that can be described, published, discovered, coordinated, and configured using open XML (a subset of the Standard Generalized Markup Language) standards, used for developing distributed, interoperable applications.\\n\\nWeb Services based on the REST architecture are RESTful.\\n\\nDue to its lightweight nature and the characteristic of transmitting data directly via HTTP, the RESTful approach to Web services has become the most common alternative. Clients can be implemented using various languages (such as Java programs, Perl, Ruby, Python, PHP, and JavaScript ).\\n\\nRESTful 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, using their web browsers to construct a GET URL and read the returned content.\\n\\nFor more introduction, you can check: RESTful Architecture Detailed Explanation\\n\\n
\\n\\n

Creating RESTful

\\n\\nFirst, create a JSON data resource file users.json with the following content:\\n\\n
{ "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 }}
\\n\\nBased on the above data, we create the following RESTful API:\\n\\n| No. | URI | HTTP Method | Content Sent | Result |\\n| --- | --- | --- | --- | --- |\\n| 1 | listUsers | GET | Empty | Display list of all users |\\n| 2 | addUser | POST | JSON string | Add a new user |\\n| 3 | deleteUser | DELETE | JSON string | Delete a user |\\n| 4 | :id | GET | Empty | Display user details |\\n\\n

Get User List:

\\n\\nIn the following code, we create the RESTful API listUsers to read the list of user information. The server.js file code is as follows:\\n\\n
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 Instance, Access Address at http://%s:%s", host, port)})
\\n\\nNext, execute the following command:\\n\\n
$ node server.js Application Instance, Access Address at http://0.0.0.0:8081
\\n\\nVisit http://127.0.0.1:8081/listUsers in your browser, and the result is as follows:\\n\\n
{ "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 }}
\\n\\n

Add User

\\n\\nIn the following code, we create the RESTful API addUser to add new user data. The server.js file code is as follows:\\n\\n
var express = require('express');var app = express();var fs = require("fs");//New user data to add 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 = user; 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 Instance, Access Address at http://%s:%s", host, port)})
\\n\\nNext, execute the following command:\\n\\n
$ node server.js Application Instance, Access Address at http://0.0.0.0:8081
\\n\\nVisit http://127.0.0.1:8081/addUser in your browser, and the result is as follows:\\n\\n
{ 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 } }
\\n\\n

Show User Details

\\n\\nIn the following code, we create the RESTful API :id (User ID) to read the detailed information of a specified user. The server.js file code is as follows:\\n\\n
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("Application Instance, Access Address at http://%s:%s", host, port)})
\\n\\nNext, execute the following command:\\n\\n
$ node server.js Application Instance, Access Address at http://0.0.0.0:8081
\\n\\nVisit http://127.0.0.1:8081/2 in your browser, and the result is as follows:\\n\\n
{ "name":"suresh", "password":"password2", "profession":"librarian", "id":2}
\\n\\n

Delete User

\\n\\nIn the following code, we create the RESTful API deleteUser to delete the detailed information of a specified user. In the following example, the user ID is 2. The server.js file code is as follows:\\n\\n
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 Instance, Access Address at http://%s:%s", host, port)})
\\n\\nNext, execute the following command:\\n\\n
$ node server.js Application Instance, Access Address at http://0.0.0.0:8081
← Nodejs ProcessNodejs Express Framework β†’