DEV Community

Cover image for How to create REST API in Nodejs?
Chetan Rohilla
Chetan Rohilla

Posted on • Updated on • Originally published at w3courses.org

How to create REST API in Nodejs?

A REST API (Web API) is an application programming interface that allows us for interaction with RESTful web services or app services. REST stands for representational state transfer. It was created by computer scientist Roy Fielding. Here we will create REST API in Nodejs.

It uses HTTP requests to access and use data. The most common HTTP requests are GET, POST, PUT, DELETE.

REST API is useful in

  1. Web Services
  2. App Services
  3. Cross Platform Applications
  4. Cloud Applications
  5. Stateless Applications
  6. Communicate different devices or platforms

REST API supports the Data formats

  • application/json
  • application/xml
  • multipart/form-data
  • application/x-wbe+xml
  • application/x-www-form-urlencoded

Securing REST APIs

  • Using HTTPS
  • Blocking access from unknown IP addresses and domains
  • Validating Input and Output
  • Blocking unexpectedly large payloads
  • Logging requests
  • Investigating failures
  • Sending Status Codes like 200,400 etc
  • Validating Clients and Devices
  • Authorizing API
  • Authenticate URLs
  • Using Headers Authorization

Create REST API in Nodejs

Step1 : Create a folder database in root directory and create a file users.json. Paste the code given below.

{
    "user1" : {
        "id" : 1,
        "name" : "Chetan"
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2 : Create a file api.js and paste the code given below.

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

/*get api*/

app.get('/list-users', function(req, res){
    fs.readFile(__dirname+'/database/users.json','utf8', function(err,data){
        res.end(data);
    });
});

/*post api*/
app.post('/create-user', function(req,res){

    fs.readFile(__dirname+'/database/users.json', 'utf8', function(err,data){
        data = JSON.parse(data);
        data["user2"] = {'id' : 2, "name": "Pankaj"};
        data = JSON.stringify(data);
        fs.writeFile(__dirname+'/database/users.json', data,function(res){
            console.log(res);
        });
        res.end(data);
    });

});

/*delete data*/

app.delete('/delete-user/:id', function(req, res){
    fs.readFile(__dirname+'/database/users.json', function(err,data){

        data = JSON.parse(data);

        delete data['user'+req.params.id];

        data = JSON.stringify(data);

        fs.writeFile(__dirname+'/database/users.json',data,function(res){
            console.log(res); //it is error response
        });

        res.end(data);

    });
});

/*create server*/

var server = app.listen(8081, function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log('Server Running at http://%s:%s',host,port);
});
Enter fullscreen mode Exit fullscreen mode

Step 3 : Install Express Node Package

Use these commands one by one

npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save
Enter fullscreen mode Exit fullscreen mode

Step 4 : Now run Node.js application
Use this command to run

node api.js
Enter fullscreen mode Exit fullscreen mode

Step 5 : To test the api run the following URLs

localhost:8081/list-users

localhost:8081/create-user

localhost:8081/delete-user/1

You can replace localhost with your domain or IP

How to Create REST API in Node Js

See the Video


See Also

How to Create Multiple Parameters Dynamic Routes in Laravel

Laravel 8 Multiple Database and Resource Routes with Controllers

Optimize Database Queries in Laravel

Flash Messages in AngularJS

Create Filters in AngularJS


Thanks For Reading :)

Please give your comments :)

Please Must Visit My Website :)

W3Courses

Top comments (0)