Step X Step : Start with NodeJS to create REST API with CRUD operations over MongoDB

Dears,

As one of the long list of Posts targeting the  Mean Stack, as i’ve already published a couple of posts targeting MongoDB for MS Windows Users and Linux Users , we will illustrate in this post how to build a REST API using NodeJS over MongoDB and a simple Client to Use the API.

Assumption

I will assume that you already know  what is NodeJS and also will assume that you installed MongoDB in your Local Machine (for detailed step x step reference , get back to my post here).

Note that its all JavaScript and nothing more, so you must be scripting lover to stand until the end of the post.

Step 1 : Installing the NodeJS Prerequisites

NodeJS is a Server Side Artifact, it means it is not Client Exposed JavaScript, so you have to know that while we moving through the Post steps, its not the real case to have the NodeJS and the Client project in the same device.

Now, lets start.

1 – Create a Folder anywhere in your machine, for my demo will be on the Desktop, Name it Node Scripts.

2 – Open Node.js command prompt and navigate to the created folder

cd C:\Users\sselim\Desktop\Node Scripts

3 – Install the Express Module in your Project

npm install express

Note that Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications and as we are going to use NodeJS to expose Crud Functions as a REST HTTP APIs, so we have to install it.

3 – Install the MongoDB Module in your Project

npm install mongodb

This is Mandatory indeed to let the NodeJS Express Compiler to understand the MongoDB Scripting we are going to build in farther step.

4 – Install the Body Parser Module in your Project

npm install body-parser

Like any CRUD Operations (GET, POST, PUT, DELETE), to let the Post Method to read from the request body and parse the contents and start using, you have to install the body-parser module first.

5 – Install the Multer Module in your Project

npm install multer

Multer is a NodeJS middleware for handling multipart/form-data

by reaching this step you installed all the prerequisites required for compiling and running your code and you have to find a folder with name node_modules created inside your project root folder (Node Scripts in my case) and inside this folder you will find 4 folders created (one for each module installed).

Step 2: Scripting the REST API

we are going to build a REST Function using NodeJS Syntax and compile using the Express and access using simple HTTP request.

I will work on a Film model with three Props. (Name, Language, Category), so we will start building the Controller JS that holds the CRUD methods for this Model.

1 – Inside the last created folder (Node Scripts) create a JS file and name it Film.js.

2 – In the created blank JS file we will start including the installed modules references

var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer();
var MongoClient = require('mongodb').MongoClient, format = require('util').format;

var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));

3 – Add a line for MongoDB Connection String

var ConnectionString = 'mongodb://127.0.0.1:27017/';

4 – Create the Server object to listen to requests to the Port of interest (i will use 8080 for my Demo)

var server = app.listen(8080, function () {
    console.log("FILMS API running at http://127.0.0.1:8080");
});

Note that as i mentioned before, the IP is 127.0.0.1 (localhost) and you should replace with the production IP when it comes to real work.

Step 3: CRUDing

We will create four function for covering the (Get All, Get By Key, Insert, Delete and Update) over the Film model.

1 – GetAll (Get Function read no parameters or even from the body)

app.get('/GetAll', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .find({})
                           .toArray(function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

2 – GetByKey (Get Function Reads the Film Name parameter ‘Key’ from the request URL Parameters )

app.get('/GetByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .find({ "Name": req.params.key })
                           .toArray(function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

3 – UpdateByKey (Post Function Reads the Film Name parameter ‘Key’ from the request URL Parameters and parse the new Film object from the the quest body)

app.put('/UpdateByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .replaceOne({ "Name": req.params.key }, req.body
                           , function (err, docs) {
                               if (docs)
                                   res.json(docs);
                               else
                                   res.json(new Array());
                           });
    });
});

4 – InsertByKey (Post Function  parse the Film object from the the quest body)

app.post('/Insert', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .insertMany(req.body
                           , function (err, docs) {
                               res.json('Done');
                           });
    });
});

5 – DeleteByKey (Get Function Reads the Film Name parameter ‘Key’ from the request URL)

app.get('/DeleteByKey/:key', function (req, res) {
    MongoClient.connect(ConnectionString + 'mongonodetest', function (err, db) {
        if (err) throw err;
        var collection = db.collection('Films')
                           .deleteMany({ "Name": req.params.key },
                            function (err, docs) {
                                res.json('Done');
                            });
    });
});

Now your REST API is ready, one last step is to run the API to be available for HTTP requests, or to make the server object we created above specific socket (IP:Port) to start listening to requests.

Do this by writing the command inside the Node.js command prompt

node Films.js

a line display the following should come up

FILMS API running at http://127.0.0.1:8080

Step 4 : Creating the Client

Now, lets build a very simple AJAX calls to request the NodeJS APIS at the Predefined Socket (127.0.0.1:8080), here and to me real MeanStacker, you should use AngularJS to do this step, but for sake of generalization and focus on the concept of (Client/Server) communication, i will use the most regular AJAX calls.

1 – Request Insert Film

Create the Followoing Class inside the Client JS file as a Client representation for the Film Model.

function Film(_Name, _Language, _Category) {
    this.Name = _Name;
    this.Language = _Language;
    this.Category = _Category;
}

Then Create a Function to Request the Remote NodeJS REST Inset function

function InsertFilms() {
    var Films = new Array();
    Films.push(new Film('Home Alone','English','Comedy'));
    Films.push(new Film('Night For Counting Years','Arabic','Drama'));
    $.ajax({
        type: "POST",
        data: JSON.stringify(Films),
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/Insert",
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

2 – Get ALL Films

function GetAllFilms() {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/GetAll",
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

3 – Gey By Film Name

function GetFilmByName(filmName) {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/GetByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

4 – Update Film

function UpdateFilm(filmName, filmObject) {
   $.ajax({
        type: "PUT",
        data: JSON.stringify(filmObject),
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/UpdateByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

5 – Delete Film By Name

function DeleteFilmByName(filmName) {
    $.ajax({
        type: "GET",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        url: "http://127.0.0.1:8080/DeleteByKey/"+filmName,
        dataType: "json",
        processdata: true,
        success: function (data) {
            alert(data);
        },
        fail: function (error) {
            alert(errors);
        }
    });
}

and we done, you can create an html page and test your code as you like , but usually don’t forget to run the Controller JS file before you start requesting it.

Advertisements

One thought on “Step X Step : Start with NodeJS to create REST API with CRUD operations over MongoDB

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s