YouTube Icon

Develop RESTful API using Node JS, Express JS




Develop RESTful API using Node JS, Express JS

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.

http://localhost:8081

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.

Also Read:- How to Build a Real-time Chat App With NodeJS, Socket.IO, and MongoDB



Author Biography.

Lokesh Gupta
Lokesh Gupta

Overall 3+ years of experience as a Full Stack Developer with a demonstrated history of working in the information technology and services industry. I enjoy solving complex problems within budget and deadlines putting my skills on PHP, MySQL, Python, Codeigniter, Yii2, Laravel, AngularJS, ReactJS, NodeJS to best use. Through Knowledge of UML & visual modeling, application architecture design & business process modeling. Successfully delivered various projects, based on different technologies across the globe.

Join Our Newsletter.

Subscribe to CrowdforThink newsletter to get daily update directly deliver into your inbox.

CrowdforGeeks is where lifelong learners come to learn the skills they need, to land the jobs they want, to build the lives they deserve.

CrowdforGeeks

CrowdforThink is a leading Indian media and information platform, known for its end-to-end coverage of the Indian startup ecosystem.

CrowdforThink

Our mission is "Har Koi Dekhe Video, Har Ghar Dekhe Video, Ghar Ghar Dekhe Video" so we Provide videos related to Tutorials, Travel, Technology, Wedding, Cooking, Dance, Festivals, Celebration.

Apna Video Wala
CFT

News & Blogs

41aa280eef897eb68aed34341b0f5425.png

Best Node.js Frameworks for App Development in ...

Node.js has made quite a name for itself in the last few years. The increasing demand for web app...

db3dea5fd7cf69805e438fb629ed4977.png

What Makes the Best Website Homepage Design? Co...

Page layout design can assist you in determining not only which material to utilize and where to ...

449d4afbbedaaf5c3f17ee0d225c7edb.png

A Simple CRUD App Using GraphQL, NodeJS, and Mo...

In my last article, I gave a global introduction to GraphQL. I compared it with REST, as the two ...

Top Authors

Lamia Rochdi is the Marketing Manager at Bell Flavors & Fragrances EMEA. A successful family-...

Lamia Rochdi

I’m Mertin Wilson a technician in a camera company and certified expert of different P...

Mertin Wilson

Zakariya has recently joined the PakWheels team as a Content Marketing Executive, shortly after g...

Zakariya Usman

Pankaj Singh is a Senior Digital Marketing Consultant with more than 2 years of experience in SEO...

Pankaj Singh
CFT

Our Client Says

WhatsApp Chat with Our Support Team