How to Create a Fake REST API Server using Node.js

How to Create a Fake REST API Server using Node.js

How to make a REST API Server using Node.js for testing your AJAX client side.

In this post, I want to show you how to create a fake REST API Server, using Node.js. This will be just a Server to test AJAX at your client side. In addition to it, it added support for CORS and request verbs like (POST, GET, DELETE, PUT). 

First of all, create a folder (RESTAPI)  and create a JSON file, as shown below. I used the file mentioned in the link above for sample JSON data.

{  
   "user1" : {  
      "name" : "mahesh",  
      "password" : "password1",  
      "profession" : "teacher",  
      "id": 1  
   },  
   "user2" : {  
      "name" : "suresh",  
      "password" : "password2",  
      "profession" : "librarian",  
      "id": 2  
   },  
   "user3" : {  
      "name" : "ramesh",  
      "password" : "password3",  
      "profession" : "clerk",  
      "id": 3  
   }  
}  

From start menu, open Node.Js command prompt and change the directory, where our folder is located and type the command given below.

npm install express --save

Create a JavaScript file, add the piece of code and name it server.js. 

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

//enable CORS for request verbs
app.use(function(req, res, next) {  
  res.header("Access-Control-Allow-Origin", "*");  
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
  res.header("Access-Control-Allow-Methods","POST, GET, PUT, DELETE, OPTIONS");  
  next();  
});  

app.use(bodyParser.urlencoded({  
    extended: true  
}));  

app.use(bodyParser.json());  

//Handle GET method for listing all users
app.get('/listUsers', function (req, res) {  
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {  
       console.log( data );  
       res.end( data );  
   });  
})  

//Handle GET method to get only one record
app.get('/:id', function (req, res) {  
   // First read existing users.  
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {  
       users = JSON.parse( data );  
       console.log(req.params.id);  
       var user = users["user" + req.params.id]   
       console.log( user );  
       res.end( JSON.stringify(user));  
   });  
})  

//Handle POST method
app.post('/addUser', function (req, res) {  
   // First read existing users.  
       fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {  
       var obj = JSON.parse('[' + data + ']' );  
       obj.push(req.body);  
       console.log(obj);  

       res.end( JSON.stringify(obj)  );  
   });  
})  

//Handle DELETE method
app.delete('/deleteUser/:id', function (req, res) {  

   // First read existing users.  
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {  
       data = JSON.parse( data );  

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

       console.log( data );  
       res.end( JSON.stringify(data));  
   });  
})  

//Handle GET method
app.put('/updateUser/:id', function(req,res){  

    // First read existing users.  
    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {  
       //var obj = JSON.parse('[' + data + ']' );  
       data = JSON.parse( data );  
       var arr={};  
       arr=req.body;  

        data["user" + req.params.id]= arr[Object.keys(arr)[0]] ; //  req.body;   //obj[Object.keys(obj)[0]]  

        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)  

})  

Notice

The parameter (data) of the request handler method is supposed to be an array of JSON objects but it didn't accept the normal array methods like (push) method, so I decided to parse it with the brackets [ ]. 

var obj = JSON.parse('[' + data + ']' );     

To run this Server, open node.js command prompt and run the command. 

$ node server.js

Now, the Server is running and now you have a REST API Server, which supports CORS for the requests. 

Here, it is listening at port 8081. To test our Server, this is the sample data for the testing purpose.

Here, it is listening at port 808. To test our Server, this is a sample data for the testing purpose.

This is image title

I hope it comes in handy. Thank you for reading !

Node.js REST API Server json AJAX node-js

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Use FeathersJS to build a RESTful API server in Node.js

In this article, you’ll learn how to build a RESTful API server in Node.js using Feathers.js

Consume Web API Post method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about how to consume Web API Get method and display records in the ASP.NET View. Here, ...

Consume Web API Get method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, I will discussed about How to Consume Web API Get method in ASP NET MVC. Blog : http://aspdotnetexplorer...

Consume Web API Put method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, we learned how to consume Web API Get and Post methods in the ASP.NET View. Here, we will see how to con...

Consume Web API Delete Method in ASP NET MVC | Calling Web API | Rest API Bangla Tutorial

LIKE | COMMENT | SHARE | SUBSCRIBE In this tutorial, we learned how to consume Web API Get,Post and PUT methods in the ASP.NET View. Here, we will see how to...