Skip to main content

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

Comments

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.



Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.



Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.



Once we select asp.net core application it will appear the following dialog.



Now w…

Solution: gulp is not recognized as internal or external command- Visual Studio

Recently, After Upgrading to the newer version of Gulp, I was getting this error.  After doing lots of  finding online and in my system I was able to figure out that Modules like Gulp does not installed to the path. So when you try to run it from the command line it was showing below error.
gulp is not recognized as internal or external command How to solve : gulp is not recognized as internal or external command To solve this error we just need to create a new environment variable and set the NPM modules path there.

To create an environment variable,  Right click My Computer/ This Pc and click on properties.  It will open following windows.



Go to Advance System Settings and it will open system properties windows like below.



Click on Environment Variables it will open an environment and system variables windows like below.



Click on new System variable and put NODE_PATH in system variable name and %AppData%\npm\node_modules into the variable value like below.



Click on Ok. That’s it. N…