Sunday, January 1, 2017

Node.js using RestFul api - Part 1 of 4

Hello everyone,

I would like to start this 2017 explaining/publishing four different articles for 'how NODE.js can communicate with RESTFUL API and how easy we can write samples of this' by the end of the explanation. First of all, I will cover the concepts and then start providing the content of what we are exchanging in order to facilitate the explanation. So, let's move it on! 

What is the RESTFUL WevService

A collection of open protocols and standards used for exchanging data between applications or systems, this is web services. Software applications written in various programming languages and running on various platforms can use web services to exchange/transfer 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 webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, that shows resource representation such as JSON and set of HTTP Methods.


What is the REST Architecture

REST stands for Representational State Transfer. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST is web standards based architecture and uses HTTP Protocol. REST was first introduced by Roy Fielding in 2000.
Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML but JSON is the most popular one.A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. 

HTTP - methods related

Following four HTTP methods are commonly used in REST based architecture.

  • PUT - It is used to create a new resource/feature
  • DELETE - It is used to remove a resource/feature

  • GET - It is used to provide a read only access to a resource/feature.
  • POST - It is used to update a existing resource or create a new resource/feature

Library- Creating Restful for it

Consider we have a JSON based database of users having the following users in a file users.json:
{ "user1" : { "name" : "Thiago","password" : "password1","profession" : "teacher", "id": 1 },"user2" : { "name" : "Leoncio","password" : "password2","profession" : "librarian", "id": 2 },"user3" : { "name" : "Arthur","password" : "password3","profession" : "clerk", "id": 3 } }
Based on this information we are going to provide following RESTful APIs.
S. N.URIHTTP MethodPOST bodyResult
1:idGETemptyProvides details of a user.
2listUsersGETemptyProvides list of all the users.
3deleteUserDELETEJSON StringDelete an existing user.
4addUserPOSTJSON StringAdd details of new user.
Most of them in the examples are hard coded assuming you already know how to pass values from front end using Ajax or simple form data and how to process them using express Request object.

ADD User

Following API will show you how to add new user in the list. Following is the detail of the new user:
user = { "user4" : { "name" : "leoncio", "password" : "password4","profession" : "teacher", "id": 4 } }
You can accept the same input in the form of JSON using Ajax call but for teaching point of view, we are making it hard coded here. Following is the addUser API to a new user in the database:
server.js
var express = require('express'); var app = express(); var fs = require("fs"); var user = { "user4" : {"name" : "mohit", "password" : "password4", "profession" : "teacher", "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 to access defined API using URL: http://phonecoding:8081/addUser and HTTP Method : POST on local machine using any REST client. This should produce following result:
{ "user1":{"name":"thiago","password":"password1","profession":"teacher","id":1}, "user2":{"name":"leoncio","password":"password2","profession":"librarian","id":2}, "user3":{"name":"Arthur","password":"password3","profession":"clerk","id":3}, "user4":{"name":"Mel","password":"password4","profession":"teacher","id":4} }

Show Detail

API to implement which will be called using user ID and it will show the detail of the related user.
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) { 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 using URL: http://127.0.0.1:8081/2 and HTTP Method : GET on local machine using any REST client. This should produce following result:
{"name":"leoncio","password":"password2","profession":"librarian","id":2}


Delete 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 user with ID 2.
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) })
Now try to access defined API using URL: http://phonecoding:8081/deleteUser and HTTP Method : DELETE on local machine using any REST client. This should produce following result:

{"user1":{"name":"thiago","password":"password1","profession":"teacher","id":1}, "user3":{"name":"Arthur","password":"password3","profession":"clerk","id":3}}

List Users - Implementation

You should implement first RESTful API listUsers using the following code in a server.js file:
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) })
Go to access defined API using URL: http://phonecoding:8081/listUsersand HTTP Method : GET on local machine using any REST client. This should produce following result:
You can change given IP address when you will put the solution in production environment.
{ "user1" : { "name" : "Thiago","password" : "password1","profession" : "teacher", "id": 1 },"user2" : { "name" : "leoncio","password" : "password2","profession" : "librarian", "id": 2 },"user3" : { "name" : "Arthut","password" : "password3","profession" : "clerk", "id": 3 } }


Part 2 of this article is coming next week.


Happy coding,
Thiago Leoncio