REST API

Build a REST API in Node

You can use Node.js to build REST APIs very easily.

In this tutorial, we would build a REST API for managing user details. Our API would be able too

 

  1. Create the JSON LIbrary
  2. Get list of users
  3. Insert a user
  4. Get a single user by Id
  5. Delete a user by Id

 

1. Create the JSON Library

As you know, if you are going to manipulate data, you need some database. In out case, we would just use data file in a directory.

The file containing list of users would be a json file named users.json.

The users file contain four fields: id, firstname, lastname and email.

The content of the user.json file is given below.

{
  "user1": {
    "id":1,
    "firstname":"Munonye",
    "lastname":"Kindson",
    "email":"kany@gmail.com"
  },

  "user2":  {
    "id":2,
    "firstname":"Imolode",
    "lastname":"Saffron",
    "email":"saffron@gmail.com"
  },

  "user3":  {
    "id":3,
    "firstname":"Munonye",
    "lastname":"Othniel",
    "email":"othniel@gmail.com"
  },

  "user4": {
    "id":4,
    "firstname":"Yuba",
    "lastname":"Oleander",
    "email":"oleander@gmail.com"
  }
}

 

2. Return a List of Users

We would now create a REST API to return a list of users by reading the users.json file. We are going to use Express Framework. You learnt this in the preceding section.

So create  a file named server.js and place it in the same directory with the users.json file. The content of the server.js file is shown below:

 

//REST API demo in Node.js
var express = require('express'); // requre the express framework
var app = express();
var fs = require('fs'); //require file system object

// Endpoint to Get a list of users
app.get('/getUsers', function(req, res){
    fs.readFile(__dirname + "/" + "users.json", 'utf8', function(err, data){
        console.log(data);
        res.end(data); // you can also use res.send()
    });
})

// Create a server to listen at port 8080
var server = app.listen(8080, function(){
    var host = server.address().address
    var port = server.address().port
    console.log("REST API demo app listening at http://%s:%s", host, port)
})

 

Now, run the program using the command

Node server.js

Then open your browser and  visit http://localhost:8080

You will a list of users which is the content of the users.json file.

 

3. Inserting a New User

We would now write the method to insert a new user. To achieve this, we would take three steps:

  • read the existing users
  • we would first create a user variable as json.
  • append the user variable into the list

I have written the code below to be added to the existing code. Here the endpoint to add a user is /addUser

//Step 1: Create a new user variable
var user = {
    "user5": {
        "id":5,
        "firstname":"Liudmyla",
        "lastname":"Nagorna",
        "email":"mila@gmail.com"
      },
} 

//The addUser endpoint
app.post('/addUser', function(req, res){
    //Step 2: read existing users
    fs.readFile(__dirname + "/" + "users.json", 'utf8', function(err, data){
        data = JSON.parse(data);
        //Step 3: append user variable to list
        data["user5"] = user["user5"];
        console.log(data);
        res.end(JSON.stringify(data));
    });
})

Now use a REST Client to make a post request to http://localhost:8080/addUser

You will get a response which is a list with the new user added. Learn how to use Advanced REST Client here.

 

4. Get User by Id

You can also get user by a particular id. So I’m going to just give you the code. Simply enter the code and then run it to see the output:

//Endpoint to get a single user by id
app.get('/:id', function (req, res) {
    // First retrieve existing user list
    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));
    });
 })

 

5. Deleting a User By id

We are now going to write the endpoint to delete a single user by id. The code is given below but note that you must access the url using a REST Client

 //Code to delete a user by id
 var id = 3;
 app.delete('/deleteUser', function (req, res) {
    // First retrieve existing users
    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       delete data["user" + 3];
        
       console.log( data );
       res.end( JSON.stringify(data));
    });
 })

If you have come this far, thumbs up! In the next sections,we would see how we can achieve these using html forms.