Full width home advertisement

The world of Angular

Basics of Angular 6 - ng6

Post Page Advertisement [Top]

APIExpressFrameworkNode.jsRESTful

How to create a basic RESTful API using Node.js and Express Framework

What is RESTful API?
REST stand for Representational State Transfer. It is an Internet Protocol that is used for creating web services. In RESTful web service resources are identified using URIs (Uniform Resource Identifier) and sends response in HTML/XML/JSON format. Set of HTTP methods like GET, PUT, POST, DELETE are typically used in a RESTful API.
Node.js
Node.js is a JavaScript cross platform framework that allows to write server-side code using JavaScript.
Express Framework
Express is web application framework that allows to write APIs for Node.js application.
Lets get started,
First we need to install Node.js. Go to below link and download Node.js installer as per your system specification and install that.
https://nodejs.org/en/download/
Now to verify whether you have successfully installed Node.js or not then run the following commands in a terminal or command prompt.

//This will display the node version
node -v

//This will display the npm (Node Package Manager) version
npm -v
If the above command displays the Node.js and npm versions that means Node.js has been installed successfully.
Now let us create a new directory called "my-rest-app"

mkdir my-rest-app

cd my-rest-app

Now run " npm nit " to create package.json file. This package.json file holds all the metadata of your project.

npm init


Now let us create a file called " index.js " inside this my-rest-app folder. This is the main entry point of our Node.js application. Also we have to install the express framework. To install express framework we need to run below command:

npm install express --save
After running this command this will update the package.json file and add the express framework details in dependency section. Also a new folder called node_modules will be created after running this command.

We have to install one more dependency i.e. " body-parser ". This module is used for parsing various MIME media types like application/x-www-form-urlencoded or application/json. So to install this we need to run the below command.

npm install body-parser --save

Let’s go ahead and set up our Express RESTful API. Edit the index.js file and import below dependencies as follow: var express = require('express'); var bodyParser = require('body-parser');

No we have to crate the Node.js express app and also we need to use body-parser with this app for parsing various MIME media types like below: var app = express(); app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded app.use(bodyParser.json()); // parse application/json //Express application will listen to port 8080 app.listen(8080, function(err){ if(err) throw err; console.log("Server is listening on ", 8080); });

Let us create some basic RESTful APIs:
ACTION HTTP METHOD ROUTES
Get all employee details GET /api/employee
Create a new employee details POST /api/employee
Update a employee details PUT /api/employee/:id
Delete a employee details DELETE /api/employee/:id
Now create a empty employees object to store the employe details.

//Employee Details
var employees = {};

GET API

//GET - Fetch all employee details
app.get('/api/employee', function (req, res) {
  res.json(employees);
});

POST API

//POST - Create a new employee details
app.post('/api/employee', function (req, res) {
  var employee = req.body;
  var employeeId = employee.id;
  if(employees[employeeId]) {
    res.json({"error": "Employee id already exists."});
  } else {
    //Set the details in employee object
    employees[employee.id] = employee;
    res.json({"success": "Employee details has been created successfully."});
  }
});

PUT API

//PUT - Update employee details
app.put('/api/employee/:id', function (req, res) {
  var employeeId = req.params.id;
  var employee = req.body;
  if(employees[employeeId]) {
    //Update the details in employee object
    employees[employeeId] = employee;
    res.json({"success": "Employee details has been updated successfully."});
  } else {
    res.json({"error": "Employee id not found."});
  }
});

DELETE API

//DELETE - Delete employee details
app.delete('/api/employee/:id', function (req, res) {
  var employeeId = req.params.id;
  if(employees[employeeId]) {
    ////Delete the details from employee object
    delete employees[employeeId];
    res.json({"success": "Employee details has been deleted successfully."});
  } else {
    res.json({"error": "Employee id not found."});
  }
});

Now to run this go to command prompt or terminal and run below command:

node index.js
//This will print - Server is listening on 8080

So the entire index.js will be like below:

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.urlencoded({'extended':'true'}));     // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                              // parse application/json

//Employee Details
var employees = {};

//GET - Fetch all employee details
app.get('/api/employee', function (req, res) {
  res.json(employees);
});

//POST - Create a new employee details
app.post('/api/employee', function (req, res) {
  var employee = req.body;
  var employeeId = employee.id;
  if(employees[employeeId]) {
    res.json({"error": "Employee id already exists."});
  } else {
    //Set the details in employee object
    employees[employee.id] = employee;
    res.json({"success": "Employee details has been created successfully."});
  }
});

//PUT - Update employee details
app.put('/api/employee/:id', function (req, res) {
  var employeeId = req.params.id;
  var employee = req.body;
  if(employees[employeeId]) {
    //Update the details in employee object
    employees[employeeId] = employee;
    res.json({"success": "Employee details has been updated successfully."});
  } else {
    res.json({"error": "Employee id not found."});
  }
});

//DELETE - Delete employee details
app.delete('/api/employee/:id', function (req, res) {
  var employeeId = req.params.id;
  if(employees[employeeId]) {
    ////Delete the details from employee object
    delete employees[employeeId];
    res.json({"success": "Employee details has been deleted successfully."});
  } else {
    res.json({"error": "Employee id not found."});
  }
});

//Express application will listen to port 8080
app.listen(8080, function(err){
  if(err) throw err;
  console.log("Server is listening on", 8080);
});

Let us create a new employee

Fetch the employee details

Update employee details

Delete employee details


No comments:

Post a Comment

Bottom Ad [Post Page]