Fake REST API Server

In this blog, 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. Here is a blog, I benefitted from, and modified the code. 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.
  1. {  
  2.    "user1" : {  
  3.       "name" : "mahesh",  
  4.       "password" : "password1",  
  5.       "profession" : "teacher",  
  6.       "id": 1  
  7.    },  
  8.    "user2" : {  
  9.       "name" : "suresh",  
  10.       "password" : "password2",  
  11.       "profession" : "librarian",  
  12.       "id": 2  
  13.    },  
  14.    "user3" : {  
  15.       "name" : "ramesh",  
  16.       "password" : "password3",  
  17.       "profession" : "clerk",  
  18.       "id": 3  
  19.    }  
  20. }  
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. 
  1. var express = require('express');  
  2. var app = express();  
  3. var fs = require("fs");  
  4. var bodyParser = require('body-parser');  
  5.   
  6. //enable CORS for request verbs
  7. app.use(function(req, res, next) {  
  8.   res.header("Access-Control-Allow-Origin""*");  
  9.   res.header("Access-Control-Allow-Headers""Origin, X-Requested-With, Content-Type, Accept");  
  10.   res.header("Access-Control-Allow-Methods","POST, GET, PUT, DELETE, OPTIONS");  
  11.   next();  
  12. });  
  13.   
  14. app.use(bodyParser.urlencoded({  
  15.     extended: true  
  16. }));  
  17.   
  18. app.use(bodyParser.json());  
  19.   
  20. //Handle GET method for listing all users
  21. app.get('/listUsers'function (req, res) {  
  22.    fs.readFile( __dirname + "/" + "users.json"'utf8'function (err, data) {  
  23.        console.log( data );  
  24.        res.end( data );  
  25.    });  
  26. })  
  27.   
  28. //Handle GET method to get only one record
  29. app.get('/:id'function (req, res) {  
  30.    // First read existing users.  
  31.    fs.readFile( __dirname + "/" + "users.json"'utf8'function (err, data) {  
  32.        users = JSON.parse( data );  
  33.        console.log(req.params.id);  
  34.        var user = users["user" + req.params.id]   
  35.        console.log( user );  
  36.        res.end( JSON.stringify(user));  
  37.    });  
  38. })  
  39.   
  40. //Handle POST method
  41. app.post('/addUser'function (req, res) {  
  42.    // First read existing users.  
  43.        fs.readFile( __dirname + "/" + "users.json"'utf8'function (err, data) {  
  44.        var obj = JSON.parse('[' + data + ']' );  
  45.        obj.push(req.body);  
  46.        console.log(obj);  
  47.          
  48.        res.end( JSON.stringify(obj)  );  
  49.    });  
  50. })  
  51.   
  52. //Handle DELETE method
  53. app.delete('/deleteUser/:id'function (req, res) {  
  54.   
  55.    // First read existing users.  
  56.    fs.readFile( __dirname + "/" + "users.json"'utf8'function (err, data) {  
  57.        data = JSON.parse( data );  
  58.          
  59.        delete data["user" + req.params.id];  
  60.          
  61.        console.log( data );  
  62.        res.end( JSON.stringify(data));  
  63.    });  
  64. })  
  65.   
  66. //Handle GET method
  67. app.put('/updateUser/:id'function(req,res){  
  68.       
  69.     // First read existing users.  
  70.     fs.readFile( __dirname + "/" + "users.json"'utf8'function (err, data) {  
  71.        //var obj = JSON.parse('[' + data + ']' );  
  72.        data = JSON.parse( data );  
  73.        var arr={};  
  74.        arr=req.body;  
  75.          
  76.         data["user" + req.params.id]= arr[Object.keys(arr)[0]] ; //  req.body;   //obj[Object.keys(obj)[0]]  
  77.           
  78.         res.end( JSON.stringify( data ));  
  79.          
  80.     });  
  81. } );  
  82.   
  83. var server = app.listen(8081, function () {  
  84.   
  85.   var host = server.address().address  
  86.   var port = server.address().port  
  87.   
  88.   console.log("Example app listening at http://%s:%s", host, port)  
  89.   
  90. })  
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 [ ]. 
  1. 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.

Method Route Payload/Data
GET http://IP:8081/listUsers
GET id http://IP:8081/5
POST http://IP:8081/addUser { "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } }
DELETE http://IP:8081/deleteUser/4 { "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } }
PUT http://Ip:8081/updateUser/4 { "user4" : { "name" : "Ahmed", "password" : "password5", "profession" : "QC engineer", "id": 4 } }

I hope it comes in handy. 
Ebook Download
View all
Learn
View all