We now have a youtube channel. Subscribe!

Node.js | RESTful API

Node.js | RESTful API


Hello folks! welcome back to a new edition of our tutorial on Node.js. In this section of our tutorial on Node.js, we will be studying about RESTful API in Node.js.

REST is an acronym for REpresentational State Transfer. REST is web standard based architecture and uses the HTTP Protocol. It revolve around resource where every single component is a resource and a resource is accessed by a common interface via HTTP standard methods. REST was introduced by Roy Fielding in 2000.

A REST server provides access to resources and REST client accesses and modifies the resources using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST makes use of various representation to represent a resource like text, JSON, XML but JSON is the most popular one.

HTTP Methods

The following four HTTP methods are often used in REST based architecture -

  • GET - This is used to provide a read only access to a resource.
  • PUT - This is used for creating a new resource.
  • DELETE - This is used for deleting a resource.
  • POST - This is used for updating an existing resource or creating a new resource.


RESTful Web Services

A web service is a group of open protocols and standards used for exchanging of data between applications or systems. Software applications written in distinct programming languages and running on various platforms can use web services to exchange data over computer networks like the internet in a way similar to inter-process communications on a single system. This interoperability is due to the use of open standards.

Web services based on REST Architecture are known as RESTful web services. These web services makes use of HTTP methods to execute the concept of REST architecture. A RESTful web services normally defines a URI (Uniform Resource Identifier), a service which provides resource representation like JSON and 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" : "kennedy",
      "password" : "password1",
      "profession" : "entrepreneur",
      "id": 1
   },
   
   "user2" : {
      "name" : "bethel",
      "password" : "password2",
      "profession" : "librarian",
      "id": 2
   },
   
   "user3" : {
      "name" : "stephanie",
      "password" : "password3",
      "profession" : "clerk",
      "id": 3
   }
}

Based on the following information, we are going to give the following RESTful APIs.

Sr.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're keeping most part of all the examples in the form of hard coding supposing you already know how to pass values from front end using Ajax or simple form data and how to process them using the Express Request object.


List Users

Let's execute 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 accessing defined API making use of http://127.0.0.1:8081/listUsers and HTTP Method : GET on local machine making use of any REST client.

Output

This should produce the following result -

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

{
   "user1" : {
      "name" : "kennedy",
      "password" : "password1",
      "profession" : "entrepreneur",
      "id": 1
   },
   
   "user2" : {
      "name" : "bethel",
      "password" : "password2",
      "profession" : "librarian",
      "id": 2
   },
   
   "user3" : {
      "name" : "stephanie",
      "password" : "password3",
      "profession" : "clerk",
      "id": 3
   }
}

Add User

The following API below will show you how to add new user in the list. Following is the detail of the new user -

user = {
   "user4" : {
      "name" : "paul",
      "password" : "password4",
      "profession" : "photographer",
      "id": 4
   }
}

You can accept the same input in the form of JSON using Ajax call but for the purpose of this tutorial, we are making it hard coded.

Example

Following is the addUser API to add a new user in the database -

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

var user = {
   "user4" : {
      "name" : "paul",
      "password" : "password4",
      "profession" : "photographer",
      "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)
})

Now try accessing defined API making use of http://127.0.0.1:8081/addUser and HTTP Method : POST on local machine using any REST client.

Output

This should produce the following result -

{
   "user1":{"name":"kennedy","password":"password1","profession":"entrepreneur","id":1},
   "user2":{"name":"bethel","password":"password2","profession":"librarian","id":2},
   "user3":{"name":"stephanie","password":"password3","profession":"clerk","id":3},
   "user4":{"name":"paul","password":"password4","profession":"photographer","id":4}
}


Show Detail

Now we will implement an API which will be called using user ID and it'll show 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) {
      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)
})

Now, try to access defined API making use of http://127.0.0.1:8081/2 and HTTP Method : GET on the local system utilizing any REST client.

Output

This should produce the following result -

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

Delete User

A deleteUser API is quite similar to addUser API where we accept the input data through req.body and then based on the user ID we delete that user from the database. To keep our program simple we assume that we are deleting user with ID 2.

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

Now, try accessing defined API making use of http://127.0.0.1:8081/deleteUser and the HTTP Method: DELETE on the local machine using any REST client.

Output

This should produce the following result -

{"user1":{"name":"kennedy","password":"password1","profession":"entrepreneur","id":1},
"user3":{"name":"stephanie","password":"password3","profession":"clerk","id":3}}


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial, we will be studying about Node.js Scaling Application.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain