REST (Representational State Transfer) is web standards based architecture and uses HTTP Protocol. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. REST uses various representations to represent a resource like text, JSON, and XML but JSON is the most popular one.
Also Read:- How to Implement Real Time Notification Using Socket.io and Node.JS?
Why do we need RESTful Web Services?
REST is an architecture style for designing networked applications. REST is a lightweight alternative to mechanisms like RPC (Remote Procedure Calls) and Web Services (SOAP, WSDL, et al.). The World Wide Web itself, based on HTTP, can be viewed as an REST-based architecture. The entire modern web browsers are REST client. RESTful applications use HTTP methods (GET, POST, PUT, and DELETE) to perform CRUD operations.
Also Read:- Uploading files with ReactJS and NodeJS
Advantages:
- Simple
- Easy to use/implement
- Easy to build
- Uniform interface
- The REST API is always independent of the type of platform or languages
- Visible, reliable, and scalable
Why opt Node JS for building RESTful APIS?
Node.js is a powerful JavaScript framework built on Google Chrome’s JavaScript V8 Engine. It is used to develop I/O intensive web applications like video streaming sites, single-page applications, etc. Node.js development is open source and used by thousands of web developers around the world.
How to Develop a Blog App Using NextJS
Advantages:
- Quick & easy development
- High performance
- Run on single thread to handle multiple concurrent requests
- Easy to write API and interaction code
- Streaming support
- Monitoring possibilities
- Authentication support
- Lightweight, fast, and scalable
Also Read:- How to Build a Real-time Chat App With NodeJS, Socket.IO, and MongoDB
About Express JS:
Express is a flexible Node.js web application framework that provides a robust set of features to develop mobile and web applications. It facilitates the rapid development of Node based Web applications.
Few core features of Express framework −
- Allows setting up of middleware to respond to HTTP Requests.
- Defines a routing table which is used to perform different actions based on HTTP Method and URL.
Also Read:- Top 10 Companies Which Built their Apps with AngularJS and Node.js
Allows to the dynamic rendering of HTML Pages based on passing arguments to templates.
Step 1: Create a package.json file.
{
"name": "restapi",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.3",
"cookie-parser": "^1.4.3",
"express": "^4.16.3",
"multer": "^1.3.1"
}
}
Note: The package.json file can be created by using npm init command (recommended way).
Also Read:- Get a head start with trending Nodejs developer capabilities
Step 2: Create 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 user = {
"user4" : {
"name" : "lokesh",
"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));
});
})
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 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)
})
Note: You can add multiple routes based on your requirement.
Also Read:- What is difference between Node.js and ReactJS?
Step 3: Open CMD, execute npm install command.
Step 4: After successful installation of node modules, run below command into CMD.
node server.js
The node server will start running into port number 8081 with corresponding API Routes; you can point to the below URL to test the application.
Step 5: Testing REST APIs
We can use any of the REST Clients like Postman Chrome App or through any of the Programming languages like Java, C#, PHP, etc., to consume the APIs.
Note: The complete code reference can be downloaded from GitHub.