Home >>Nodejs Tutorial >Node.js - RESTful API

Node.js - RESTful API

Node.js - RESTful API

What is REST architecture?

REST stands for state transfer by REpresentational. REST is network standards-based architecture and uses the HTTP Protocol. It revolves around resource where every part is a resource, and a resource is accessed using standard HTTP methods via a specific interface. Roy Fielding first launched REST in the year 2000.

A REST Server essentially gives access to resources and accesses the REST client and modifies the resources using the HTTP protocol. Here the URIs / global IDs classify each resource. REST uses different representations to represent a resource such as text, JSON, XML but the most common is JSON.

HTTP methods

In REST-based architecture they are commonly used after four HTTP methods.

GET− This gives read only access to a tool.
PUT− A new resource is generated using this.
DELETE− This is for the elimination of a tool.
POST− Uses this to update an existing tool or to build a new one.

RESTful Web Services

A web service is a collection of open protocols and standards that are used to exchange data between apps or systems. Software applications written in different programming languages and running on different platforms may use web services to exchange data over computer networks such as the Internet in a manner similar to communication between processes on a single computer. This interoperability (e.g. communication between Python and Java, or applications under Windows and Linux) is due to the use of open standards.

REST Architecture-based web services are referred to as RESTful web services. These webservices employ HTTP methods to incorporate the REST architecture principle. Typically a RESTful web service describes a URI, Standard Resource Identifier a service that provides resource representation including JSON and collection of HTTP methods.

Creating RESTful for A Library

Consider we have a user database based on JSON which has the following users in a users.json file:


{
"user1" : {
"name" : "Ram",
"password" : "pswd1",
"profession" : "example1",
"id": 1
},
"user2" : {
"name" : "shyam",
"password" : "pswd2",
"profession" : "example2",
"id": 2
},
"user3" : {
"name" : "geeta",
"password" : "pswd3",
"profession" : "example3",
"id": 3
}
}

We'll provide following RESTful APIs based on this information.

I hold most of the examples as hard coding if you already know how to transfer 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 in a server.js file using the following code –

server.js

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)
})

Output:

Now try to access specified API using URL: http:/127.0.0.1:8081/listUsers and HTTP Method: GET using any REST client on a local machine. This will produce the result –

When you put the solution in the production setting, you can change provided IP address.

{
"user1" : {
"name" : "Ram",
"password" : "pswd1",
"profession" : "example1",
"id": 1
},
"user2" : {
"name" : "shyam",
"password" : "pswd2",
"profession" : "example2",
"id": 2
},
"user3" : {
"name" : "geeta",
"password" : "pswd3",
"profession" : "example3",
"id": 3
}
}

Add User

Following the API you can see how to connect new users to the list. Following is the latest app info –


user = {
"user4" : {
"name" : "Rajan",
"password" : "pswd4",
"profession" : "example4",
"id": 4
}
}

Using Ajax call you can accept the same input in the form of JSON but we are keeping it hard coded here for teaching point of view. The addUser API follows for a new user in the database –

server.js

var express = require('express');
var app = express();
var fs = require("fs");

var user = {
"user4" : {
"name" : "Rajan",
"password" : "pswd4",
"profession" : "example4",
"id": 4
}
}
app.post('/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)
})

Output:

Now try using URL to access the specified API: http:/127.0.0.1:8081/addUser and HTTP method: POST with any REST client on local machine. This will produce the result –

{
"user1":{"name":"Ram","password":"pswd1","profession":"example1","id":1},
"user2":{"name":"shyam","password":"pswd2","profession":"example2","id":2},
"user3":{"name":"geeta","password":"pswd3","profession":"example3","id":3},
"user4":{"name":"Rajan","password":"pswd4","profession":"example4","id":4}
}

Show Detail

We will now implement an API called using user ID and it will show the user information.

server.js

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) {
var users = 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)
})

Output:

Try now to access the specified API using URL: http:/127.0.0.1:8081/2 and HTTP method: GET using any REST client on a local machine. This will produce the result –

{"name":"shyam","password":"pswd2","profession":"example2","id":2}

Delete User

This API is very similar to addUser API, where we receive input data that req.body and then we remove the user from the database based on user ID. To keep our system easy we presume that with ID 2 we can delete user.

server.js

var express = require('express');
var app = express();
var fs = require("fs");
var id = 2;
app.delete('/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)
})

Output:

Now try to access the defined API using URL: http:/127.0.0.1:8081/deleteUser and HTTP Method: DELETE using any REST client on a local machine. This will produce the result –

{"user1":{"name":"Ram","password":"pswd1","profession":"example1","id":1},
"user3":{"name":"geeta","password":"pswd3","profession":"example3","id":3}}

No Sidebar ads