« Previous | 1 | 2 | 3 | Next »

Nodejs - Restful Api



What is REST Architecture?

REST stands for REpresentational State Transfer. REST is a web standard based architecture that uses HTTP Protocol. It revolves around resources where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000.

A REST Server simply provides access to resources and a REST client accesses and modifies the resources using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource, for example, text, JSON, XML, but JSON is the most popular one.

HTTP methods

The following four HTTP methods are commonly used in REST based architecture.
  • GET - This is used to provide a read-only access to a resource.
  • PUT - This is used to create a new resource.
  • DELETE - This is used to remove a resource.
  • POST - This is used to update an existing resource or create a new resource.
RESTful Web Services

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., communication between Java and Python, or Windows and Linux applications) is due to the use of open standards.

Web services based on REST Architecture are known as RESTful web services. These web services use HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier, which provides resource representation such as JSON and a set of HTTP Methods.

Creating RESTful for a Library

Consider we have a JSON based database of users having the following users in a file users.json:
{
"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 this information, we are going to provide the following RESTful APIs.

S. No.URIHTTP MethodPOST bodyResult
1listUsersGETemptyShow list of all the users.
2addUserPOSTJSON StringAdd details of new user.
3deleteUserDELETEJSON StringDelete an existing user.
4:idGETemptyShow details of a user.
We are keeping most of the part of all the examples in the form of hard-coding, assuming you already know how to pass values from the front-end using Ajax or simple form data and how to process them using express Request object.

List Users

Let's implement our first RESTful API listUsers using the following code in a server.js file:

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("Example app listening at http://%s:%s", host, port)
})

Now try to access the defined API using http://127.0.0.1:8081/listUsers on your local machine. It should produce following result:

You can change the given IP address when you will put the solution in production environment.

{
"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 Users

Following API will show you how to add a new user in the list. Following is the detail of the new user:

user = {
"user4" : {
"name" : "mohit",
"password" : "password4",
"profession" : "teacher",
"id": 4
}
}

You can accept the same input in the form of JSON using Ajax call but for demonstration purpose, we are hard-coding it here. Following is the addUser API to a new user in the database:

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) {
// First read existing users.
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("Example app listening at http://%s:%s", host, port)
})

Now try to access the defined API using http://127.0.0.1:8081/addUsers on your local machine. It should produce following result:

{ 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 Detail

Now we will implement an API which will be called using user ID and it will display the detail of the corresponding user.

var express = require('express');
var app = express();
var fs = require("fs");
app.get('/:id', function (req, res) {
// First read existing users.
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
var user = users["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("Example app listening at http://%s:%s", host, port)
})

Now let's call the above service using http://127.0.0.1:8081/2 on your local machine. It should produce following result:

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

Delete a User

This API is very similar to addUser API where we receive input data through req.body and then based on user ID, we delete that user from the database. To keep our program simple, we assume we are going to delete the user with ID 2.

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("Example app listening at http://%s:%s", host, port)
})

Now let's call the above service using http://127.0.0.1:8081/deleteUser on your local machine. It should produce the following result:

{ user1:
{ name: 'mahesh',
password: 'password1',
profession: 'teacher',
id: 1 },
user3:
{ name: 'ramesh',
password: 'password3',
profession: 'clerk',
id: 3 }
}
« Previous | 1 | 2 | 3 | Next »


copyright © 2014 - all rights riserved by javatechnologycenter.com