Create a RESTFul API Using Node.JS, Express.JS and MongoDB Database Full Tutorial
REST (Representational State Transfer) is Architectural Styles and a Design of Network-based Software Architectures. Now a days REST architecture is widely used in application development. You can use it with any application to verify or view specific information on web without invoking server side validations.
We have already discussed how to implement API using Slim micro framework and how to create RESTFul API using Node.js, Express.JS and MySQL. In this tutorial we will see how to create an API using JavaScript rest API framework NodeJS, Express and MongoDB.
Read more:
Create a RESTful Web Service API with NodeJS, ExpressJS and MySQL
Create a RESTful Web Service API with Slim framework
MongoDB is a open-source and cross-platform database, like NoSQL database. MongoDB is document-oriented database that uses JSON Documents with schemes.
Read more about basic commands that each Mongo-DB developer should know.
RESTFul API Using Node.JS, Express.JS and MongoDB
Before starting with node js MongoDB tutorial we need a hosted MongoDB server to be connect with our application. To run MongoDB server open terminal or command line if you are having windows operating system. Navigate to MongoDB directory and run below command.
1
|
bin/mongod.exe
|
To make debug easy you can install windows MongoDB client such as MongoBooster.
1
2
3
4
5
6
|
app.js
package.json
collectionDriver.js
views/
-- 404.jade
node_modules/
|
We are going to use jade template engine to render 404 page. Jade is high performance template engine implemented with JavaScript for node.
Run below command to install Node packages
1
|
$ npm install
|
It will create package.json
file. Now install Jade
by running following command.
1
|
$ npm install jade --save
|
Install body-parser
by using following command.
1
|
$ npm install body-parser --save
|
Now, we need to install express and MongoDB. It install express js use below command –
1
|
$ npm install express --save
|
It will install latest version of express and update package.json
as well. After completing installation of express finally we need to install MongoDB node package.
1
|
$ npm install mongodb --save
|
After installing all the modules our package.json
will look like
1
2
3
4
5
6
7
8
9
10
|
{
"name": "mongo-server",
"version": "1.0.1",
"private": true,
"dependencies": {
"express": "^4.15.3",
"jade": "^1.11.0",
"mongodb": "^2.2.27"
}
}
|
You can change information such as application name and version in package file.
This file will contain error message along with current URL.
1
2
3
|
doctype html
body
h1= 'Could not load page: ' + url
|
For initial setup open the app.js
and complete setup by copying below code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
parser = require('body-parser')
CollectionDriver = require('./collectionDriver').mongoWrapper;
// Creating new Express Object
var app = express();
// Set MongoDB Host
var mongoHost = 'localHost';
// Set MongoDB Port
var mongoPort = 27017;
var mongoWrapper;
// Creating MongoDB client
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort));
mongoClient.connect("mongodb://"+mongoHost+"/nodejs-shop", function(err, mongoClient) {
if (!mongoClient) {
console.error("Error! Datbase connection failed.");
process.exit(1);
}
var db = mongoClient.db("node_shop");
mongoWrapper = new CollectionDriver(db);
});
app.set('port', process.env.PORT || 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(parser.json());
app.use(parser.urlencoded({ extended: true }));
// Default route
app.get('/', function(req, res){
res.status(200).send("<html><body><p>Welcome to sShop 1.1</p></body></html>");
});
// Create 404 page
app.use(function (req,res) {
res.render('404', {url:req.url});
});
// Create server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
|
We are using nodejs-shop
database in application. Before setting port of server make sure port is not being used by another application or service. Default route is nothing but an index page from where you can double check either service started or not. We will start node server at the end of tutorial when we will be going to test the web server.
collectionDriver.js file contains all the database related functions that need to be used in later part of tutorial.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
var ObjectID = require('mongodb').ObjectID;
mongoWrapper = function(db) {
this.db = db;
};
mongoWrapper.prototype.getCollection = function(collectionName, callback) {
this.db.collection(collectionName, function(error, currentCollection) {
if( error ) callback(error);
else callback(null, currentCollection);
});
};
mongoWrapper.prototype.update = function(collectionName, obj, entityId, callback) {
this.getCollection(collectionName, function(error, currentCollection) {
if (error) {
callback(error);
} else {
obj._id = ObjectID(entityId);
obj.updated_at = new Date();
currentCollection.save(obj, function(error,doc) {
if (error){
callback(error);
} else {
callback(null, obj);
}
});
}
});
};
mongoWrapper.prototype.delete = function(collectionName, entityId, callback) {
this.getCollection(collectionName, function(error, currentCollection) {
if (error) {
callback(error);
} else {
currentCollection.remove({'_id':ObjectID(entityId)}, function(error,doc) {
if (error) {
callback(error);
} else callback(null, doc);
});
}
});
};
mongoWrapper.prototype.save = function(collectionName, obj, callback) {
this.getCollection(collectionName, function(error, currentCollection) {
if( error ) callback(error)
else {
obj.created_at = new Date();
obj.updated_at = new Date();
currentCollection.insert(obj, function() {
callback(null, obj);
});
}
});
};
mongoWrapper.prototype.findAll = function(collectionName, callback) {
this.getCollection(collectionName, function(error, currentCollection) {
if( error ) callback(error);
else {
currentCollection.find().toArray(function(error, results) {
if( error ) callback(error);
else callback(null, results);
});
}
});
};
mongoWrapper.prototype.get = function(collectionName, id, callback) {
this.getCollection(collectionName, function(error, currentCollection) {
if (error) callback(error);
else {
var exp = new RegExp("^[0-9a-fA-F]{24}$");
if (!exp.test(id)) callback({error: "Invalid product id"});
else currentCollection.findOne({'_id':ObjectID(id)}, function(error,doc) {
if (error) callback(error);
else callback(null, doc);
});
}
});
};
exports.mongoWrapper = mongoWrapper;
|
Create a route having specific URL and HTTP Method. MongoDB will create database and table on the fly so we do not need to take care it like MySQL database.
We have used post
HTTP method. You can pass any parameter for product in request MongoDB will create fields automatically based on your request parameter key.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// Endpoint: http://localhost:8080/product/add
app.post('/product/add', function(req, res) {
var object = req.body;
mongoWrapper.save('md_products', object, function(err, colRes) {
if (err) {
res.status(400).send(error);
} else {
var response = [{'status':'success', 'data':colRes}];
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
}
});
});
|
It will create a JSON
document and insert information into database such as Product name, Product Price, Product Description. We will use Postman Chrome Extension to test our App. You can install the extension from here.
Response:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
[
{
"status": "success",
"data": {
"product_name": "Mac Lion 54X",
"product_description": "Lorem Ipsum is simply dummy text of the printing ",
"product_price": "80000",
"created_at": "2017-06-04T06:53:16.397Z",
"updated_at": "2017-06-04T06:53:16.397Z",
"_id": "5933ae5c94d7b80e10398c35"
}
}
]
|
Single Product endpoint will returns entity from “md_products
” table into JSON
format based on id passed in request. if record not found having id passed by user than it will return error with 400 HTTP code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
Endpoint: http://localhost:8080/product/5933ae5c94d7b80e10398c35
app.get('/product/:id', function(req, res) {
var id = req.params.id;
if (id) {
mongoWrapper.get('md_products', id, function(error, colRes) {
if (error) {
res.status(400).send(error);
} else {
var response = [{'status':'success', 'data':colRes}];
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
}
});
} else {
res.status(400).send({error: 'Invalid request', url: req.url});
}
});
|
Response:
1
2
3
4
5
6
7
8
9
10
11
12
|
[
{
"status": "success",
"data": {
"product_name": "Mac Lion 54X",
"product_description": "Lorem Ipsum is simply dummy text of the printing ",
"product_price": "80000",
"_id": "59338560a246fa1540770ac5",
"updated_at": "2017-06-04T05:18:30.180Z"
}
}
]
|
An Edit Single Product endpoint will be used to edit specific product exists in ‘nd_products’ database table. The parameters Product name, price and image URL need to be passes in PUT
method with our request.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
Endpoint: http://localhost:8080/product/update/5933ae5c94d7b80e10398c35
app.put('/product/update/:id', function(req, res) {
var id = req.params.id, object = req.body;
if (id) {
mongoWrapper.update('md_products', object, id, function(err, colRes) {
if (err) {
res.status(400).send(error);
} else {
var response = [{'status':'success', 'data':colRes}];
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
}
});
} else {
var response = [{'status':'error', error: 'Invalid request', url: req.url}];
res.status(400).send(JSON.stringify(response));
}
});
|
Response:
1
2
3
4
5
6
7
8
9
10
11
12
|
[
{
"status": "success",
"data": {
"product_name": "Mac Lion 54X Updated",
"product_description": "Lorem Ipsum is simply dummy text of the printing ",
"product_price": "80000",
"_id": "59338560a246fa1540770ac5",
"updated_at": "2017-06-04T05:18:30.180Z"
}
}
]
|
This endpoint will check wether record is exists in database having requested id or not. If record found the it will delete the record by calling mongoWrapper.delete()
function. If record does not exists in database than it will return error with 400 HTTP code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
Endpoint: http://localhost:8080/product/delete/5933ae5c94d7b80e10398c35
app.delete('/product/delete/:id', function(req, res) {
var id = req.params.id;
if (id) {
mongoWrapper.delete('md_products', id, function(error, colRes) {
if (error) {
res.status(400).send(error);
} else {
var response = [{'status':'success', 'data' : colRes}];
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
}
});
} else {
res.status(400).send({error: 'Invalid request', url: req.url});
}
});
|
Response:
1
2
3
4
5
6
7
8
9
|
[
{
"status": "success",
"data": {
"n": 1,
"ok": 1
}
}
]
|
We have completed crud operations in Nodejs server. Now open your command line Run your application by node app.js
command. Open “http://127.0.0.1:8080
” in browser to see the output.
Read More:
Create RESTful API Using Node.JS, Express and MySQL
Create a RESTful Web Service API with Slim
How to Create Database in MongoDB
Integrate PayUMoney Payment gateway in PHP
How To Integrate Stripe Payment Gateway Using PHP and JavaScript
sSwitch – JQuery Toggle Button Plugin For Sliding Toggle Switches