MEAN Tutorial (Part 3) : Build REST API’s with node express and mongo.

July 10, 2015
by Inaam Hussain

In this tutorial will learn how to create REST API’s using Node js, MongoDB and Express 4.
Using Express 4 we can easily manage GET, POST, PUT & DELETE requests.
 

DEMO DOWNLOAD

Let’s start with installing dependencies and then the code,

 

Install dependencies

We are going to use following node modules for handling session.

  1. Express 4
  2. Body parser
  3. Mongoskin

I have created a package.json file that will install all required dependencies.

package.json
{
    "name": "Node-mongodb-access",
    "version": "0.0.1",
    "main": "server.js",
    "dependencies": {
            "express": "^4.8.7",
            "body-parser":"^1.12.0",
            "mongoskin":"^1.4.12"
        }
}

 

How to install dependencies?

Add the above package.json into your project folder and run the below command.

npm install

Note : You must also have MongoDB installed if you are working locally.

 

Initialization & Require

Note : Before starting this first Run mongodb see Here

Here we require the necessary node-modules and also connect to our Database in MongoDB.

server.js
var app   = require('express')(); // Require Express module
var http = require('http').Server(app); // Http server
var bodyParser = require("body-parser"); // Require Body parser module
var mongo = require('mongoskin'); // Require mongoskin module
var db = mongo.db("mongodb://localhost:27017/books", {native_parser:true}); // Connection MongoDB book collection DB
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // Body parser use JSON data
app.use(function(req,res,next){
    req.db = db;
    res.header('Access-Control-Allow-Origin', '*'); // We can access from anywhere
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    next();
});

 

Http Server Run

Using http.listen(Port number) server will run defined port number.

server.js
http.listen(8080,function(){
    console.log("Connected & Listen to port 8080");
});

 

Show List Of Books API

Using below API we will fetch all books with it’s data.

server.js
app.get('/book',function(req,res){
    var data = {
        "Data":""
    };
    var db = req.db;
    db.collection('books').find().toArray(function (err, items) {
        if(items.length != 0){
            data["error"] = 0;
            data["Books"] = items;
            res.json(data);
        }else{
            data["error"] = 1;
            data["Books"] = 'No books Found..';
            res.json(data);
        }
    });
});
Get all books Response

Get all books Response

First we will define route url (i.e : app.get(‘/book’,function()) ).
And then make sql query to fetch all book data using db.collection('books').find(). and format that data in array using toArray() function. That will fetch all book data and return as json. which you can see in above image and code.
 

Add New Book API

Using below API we will add new book data to mongodb database.

server.js
app.post('/book',function(req,res){
    var Bookname = req.body.bookname;
    var Authorname = req.body.authorname;
    var Price = req.body.price;
    var data = {
        "error":1,
        "Books":""
    };
    if(!!Bookname && !!Authorname && !!Price){
        db.collection('books').insert({bookname:Bookname , authorname: Authorname, price:Price}, function(err, result) {
            if(!!err){
                data["Books"] = "Error Adding data";
            }else{
                data["error"] = 0;
                data["Books"] = "Book Added Successfully";
            }
            res.json(data);
        });
    }else{
        data["Books"] = "Please provide all required data (i.e : Bookname, Authorname, Price)";
        res.json(data);
    }
});
Add New Book Response

Add New Book Response

First will define route url (i.e : app.post(‘/book’,function()) ).
And then make data object which you want to add book data to database using db.collection('books').insert({object}). That will add book data and based on that return response as json. which you can see in above image and code.
 

Update Existing Book API

Using below API we will update existing book data to mongodb database.

server.js
app.put('/book',function(req,res){
    var Id = req.body.id;
    var Bookname = req.body.bookname;
    var Authorname = req.body.authorname;
    var Price = req.body.price;
    var data = {
        "error":1,
        "Books":""
    };
    if(!!Bookname && !!Authorname && !!Price){
        db.collection('books').update({_id:mongo.helper.toObjectID(Id)}, {$set:{bookname:Bookname,authorname:Authorname,price:Price}}, function(err) {
            if(!!err){
                data["Books"] = "Error Updating data";
                console.log("second");
            }else{
                data["error"] = 0;
                data["Books"] = "Updated Book Successfully";
            }
            res.json(data);
        });
    }else{
        data["Books"] = "Please provide all required data (i.e : Bookname, Authorname, Price)";
        res.json(data);
    }
});
Update Existing Book Response

Update Existing Book Response

First we will define route url (i.e : app.put(‘/book’,function()) ).
And then make data object which you want to update book data to database using db.collection('books').update({object}). That will update book data and based on that return response as json. which you can see in above image and code.
 

Delete Existing Book API

Using below API we will delete existing book data to mongodb database.

server.js
app.delete('/book/:bookname',function(req,res){
    var BookName = req.params.bookname;
    var data = {
        "error":1,
        "Books":""
    };
    if(!!BookName){
        db.collection('books').remove({bookname:BookName}, function(err, result) {
            if(!!err){
                data["Books"] = "Error deleting data";
            }else{
                data["error"] = 0;
                data["Books"] = "Delete Book Successfully";
            }
            res.json(data);
        });
    }else{
        data["Books"] = "Please provide all required data (i.e : bookname )";
        res.json(data);
    }
});
Delete Existing Book Response

Delete Existing Book Response

First we will define route url (i.e : app.delete(‘/book/:bookname’,function()) ).
In :bookname will get request data from front-end.
And then make data object which you want to delete book data to database using db.collection('books').remove({object}). That will delete book data and based on that return response as json. which you can see in above image and code.
 

How to run?

First check whether you have installed Node.js or not.
Then install all required dependencies (i.e : express, mongoskin & body-parser ) by typing following command in terminal,

npm install

Now, run the server using following command.

node server.js

And now go to postman and hit localhost:8080/RoutesUrl. for checking APIs.
 

About

Engineer. Blogger. I like to be updated on new upcoming emerging technologies.

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

Leave a Comment