Sunday, January 22, 2017

Building Node.js CRUD Rest APIs with Express and Visual studio code

TL;DR;

In this blog post, we are going to learn how we can create a basic Rest API with Node.js and Express using Visual Studio code editor.  Our API will contain four operations CREATE, READ, EDIT and DELETE.

Creating Basic Node Express application and common code for REST APIs:

The first thing we need to create an empty folder called NodeJSRestPI folder and then right click and select open with code.

open-folder-with-visual-studio-code

Once you open visual studio code create a file called package.JSON and put following JSON content on that.
{
    "name": "node-api",
    "main": "api.js",
    "dependencies": {
        "express": "4.14.0",
        "body-parser": "1.16.0"
    }
}
Here you can see that we are going to use express and body parser npm.  Express is framework for creating Rest APIs and body-parser is to parse body values in JSON. Now once we are done with package.json we need to install node js module via “npm install”. With Visual Studio code, You can directory open command line via clicking on Ctrl + ` Shortcut and then you can run any commands there like following.

npm-install-visual-studio-code-console

Now let’s create a file called API.js and put following JavaScript code into that.
var express = require("express");
var app = express();
var bodyParser = require("body-parser");

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

var port = process.env.port || 3000;
var router = express.Router();

app.use('/api/employee', router);
app.listen(port);
Here you can see this code is pretty standard code for any express application. Here we  are creating express object with require syntax and then use that app object to create a router and then we have created a port and our app is listening on that port. So our basic application is ready. Now let’s add some common JavaScript code which we are going to use through out whole application.

Since this application is for demo purpose only we are not going to use any database for that and we are going to use a static JavaScript object for our CRUD operations. Following is code for our employee's object. Here you can see it is an array of JavaScript objects of employees. Basically, it contains an array of employee objects. By default, I have put one record there.
var employees= [
    {
        Id: 1,
        FirstName: "Jalpesh",
        LastName: "Vadgama",
        Designation: "Technical Architect"
    }
];
Another common JavaScript function we are going to use for validation of employee object. Basically, it checks object properties of Employee object. It returns true if the object has all the valid properties otherwise, it will return false. Following is code for the same.
//validation for employee
function isValidEmployee(employee){
    if(!employee.Id){
        return false;
    }
    if(!employee.FirstName){
        return false;
    }
    if(!employee.LastName){
        return false;
    }
    if(!employee.Designation){
        return false;
    }
    return true;
}
Now we are done with all the code. It’s time to write some code for creating actual operations.

ReadAll/GetAll Operation:

Here we are going to return all the employees available. In our case, we are going to return current employees JavaScript Object. Following is code for the same.
// Get all employees
router.get("/",function (req,res){
    res.json(employees);
});
Here in the above code, you can see that we use GET HTTP verb returning all the employees available. and Created a get HTTP operation. Now when you run it in postman it will return like following.

getall-with-nodejs-rest-api

Read specific/Get single operation:

In this specific operation, we are going to pass employee id in URL and it will return an employee object available. Following is a code for that.
//get specific employee based on Id
router.get("/:Id",function(req,res){
    var employeeId = parseInt(req.params.Id);
    var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];

    if(currentEmployee){
        res.json(currentEmployee);
    }else{
        res.sendStatus(404);
    }
});
Here in the above code, you can see that we have created get operation, First, we are getting employee id and based on that we are filtering our employees object and getting a current specific employee. If an employee is there we are returning that employee object as JSON else we are sending 404 statuses not found.

Once you run with the postman. It will look like following.

specific-get-node-js-employee

Add/CREATE Employee:

In this operation, We are going to create a POST operation with express and we are going to have employee object as Request body. We are going to validate the employee object with our common validation function. Based on validation function result if all  required properties are available then we are going to add to our exiting employees collection object or else we are going return internal server status. Following is code for that.
/// Add employee
router.post("/", function (req,res) {
    var employee = req.body;
    var isValid =isValidEmployee(employee);
    if(isValid){
        employees.push(employee);
        res.send(employee);
    } else{
        res.sendStatus(500);
    }
});
Here is how it look in postman.

add-employee-nodejs-api

Update/Edit operation:

Here for an update operation, We are going to use PUT HTTP verb.  In this function, we are going to check that whether this employee exists or not. If exist we will update the properties of particular specific employee object and send code 204 which says operations completed successfully.  If the employee does not exist then it will return 404-Not found. Following is code for that.
router.put("/:Id",function (req,res) {  
    var employeeId = parseInt(req.params.Id);
    var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];
    if(currentEmployee){
        let employee = req.body;
        var isValid = isValidEmployee(employee);
        if(isValid){
            currentEmployee.FirstName = employee.FirstName;
            currentEmployee.LastName = employee.FirstName;
            currentEmployee.Designation = employee.Designation;
            res.sendStatus(204);
        }else{
            res.sendStatus(500);
        }
    }else{
        res.sendStatus(404);
    }
});
And when you run this in postman, It looks like following.

update-employee-nodejs-api

Delete operation:

In this operation, We are going to use DELETE HTTP verb. We are going to check that whether this employee id passed exist or not. If exists, we will delete that employee from our collection object and return 204 statuses. If not found then we are going to have 404 statuses. Following is code for the same.
//delete employee
router.delete("/:Id", function(req,res){
    var employeeId = parseInt(req.params.Id);
    var currentEmployee = employees.filter(e=>e.Id==employeeId)[0];
    if(currentEmployee){
        employees = employees.filter(e=>e.Id!=employeeId);
        res.sendStatus(204);
    }else{
        res.sendStatus(404);
    }
});
Now when you run in postman. It will look like this.

delete-employee-nodejs-api

That’s it. Hope you like it. In this next post, we are going to see how we handle validation in the better way with Node.js APIs.

Complete source code of this blog post is available on Github at following location- https://github.com/dotnetjalps/NodeJsRestAPI

You can run this API with the following command.

node api.js 
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews