The basic purpose of this post is to explain the concept about how we can develop REST API (web services) using node.js, express.js framework and Mongo DB using mongoose .
For the purpose of this blog I am using my local PC as development environment. This example talks about a Restaurant that serves Breakfast, Lunch, Supper, Dinner etc. Each food category has a banner image and each category has a list of food (burger, pizza, coke, etc) with their banner images.
YO! Why should I have to learn this? I am mobile developer.
Typically, mobile app developers are less bothered about looking into how the APIs are structured internally. All they are concerned for, is to look for the request/response pair and their implementation.
There are challenging times when the team has to identify solutions to complex business logic and has to find out the most apt way to resolve that. In situations like this, every knowledge in the team counts. API development experience in such cases helps you to devise better solutions.
Let’s start the hack
First of all, it requires the environment setup for node JS, Mongo DB, express Framework and related modules. Hereby, I am preparing the different posts for setting up all the above mentioned required js and framework so that this post can be clean and only point to API development. Follow the below links for setup each.
- Introduction and Environment Setup of Node JS.
- Introduction and Environment Setup of Express framework, express generator and related modules.
- Introduction and Environment Setup of Mongo Database.
- Introduction and Environment Setup of Mongoose.
After setting up everything, let’s create the project using express generator by running the command express in command prompt, and it will generate the basic project structure with files and directory. Check in detail about express generator and project creation.
Project structure created by express command
Package.json file is the manifest of this project, whatever dependency you install and use in this project, it must be mentioned in this file in the dependency section.
package.json
In bin directory there is a file named as www which is the entry point of this project. This file also set the port at which this local node server run:
var port = normalizePort(process.env.PORT || ‘3000’);
//You can change this 3000
app.set(‘port’, port);
After setting up everything we have to start local Mongo database server as mentioned in Environment Setup of Mongo Database.
Create connection with Mongo database using Mongoos JS
In your app.js write the following code —
var mongoose = require(‘mongoose’);
var url = ‘mongodb://127.0.0.1:27017/Restaurant’;
// 27017 is local port at ehich your Mongo server is running
// Restaurant is your document/database name and
mongoose.connect(url);
var db = mongoose.connection;
db.on(‘error’, console.error.bind(console, ‘connection error’));
db.on(‘open’, function(){
console.log(‘Connected’);
});
Create API for Categories
At first, we have to decide what we will put in this category and then create a schema (using mongoose schema). For the sake of understanding, we could say Schema is like a model. Let’s create a directory named as model inside my project and now I am keeping all the schema/model file inside this directory.
Category-Model.js
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var categoryModel = new Schema({
name: {
type:String,
require:true,
unique:true
},
banner: {
type:String,
require:false
},
description: {
type:String,
require:false
}
},
{
timestamps:true //Add two field automatically, createAt, updateAt
});
var Category = mongoose.model(“category” ,categoryModel);
module.exports = Category;
Now under routes directory, create js file in which the entire API development related code for category resides (GET, POST, PUT, DELETE). I am doing this with name category-router.js.
Import the required files
var express = require(‘express’);
var mongoose = require(‘mongoose’);
var bodyParser = require(‘body-parser’);
var category = require(‘../model/category-model.js’);
var categoryRouter = express.Router();
categoryRouter.use(bodyParser.json());
Create the GET API which will fetch the entire category.
categoryRouter.route(‘/’)
.get(function(req,res){
category.find({}, function(err, category){
if(err){
return fails(res, err);
} else{
successGet(res,category);
}
//200, application/json
});
});
Create the POST API which will add category with a banner image.
categoryRouter.route(‘/’)
.post(function(req, res,next){
upload(req, res, function(err){
if(err){
// An error occurred when uploading
return fails(res, err);
} else{
// Everything went fine
if(req.file ==- null || req.file === ‘undefined’){
addCategory(req.body.name,”,req.body.description,res);
} else{
addCategory(req.body.name,req.file.path,
req.body.description,res);
}
}
});
});
function addCategory(name, url, description, res) { category.create({“name”:name,”banner”:url,”description”:description}, function(err, data){
if(err){
if (err.name === ‘MongoError’ && err.code === 11000) {
// Duplicate category insertion
return fails(res, ‘Category already exist!’);
}
return fails(res, err);
} else{
success(res, data);
}
res.end();
})
}
Support functions which is required to print the Json response in each API response.
function successGet(res, data){
if(data === null || data[0] === null || data[0] === ‘undefined’){
fails(res, “No item available”)
} else{
res.json({
success: true,
message: “”,
data: data
});
}
}
function success(res, data){
if(data === null){
fails(res, “No category available”)
} else{
res.json({
success: true,
message: “”,
data: data
});
}
}
function fails(res, err){
return res.status(500).send({ succes: false, message: err });
}
For the complete code clone from git- repository.
For testing our API, we need to first verify that Our Mongo DB server is already running and now start node server by using npm start command in command prompt, from the project directory.
npm start
Now everything is connected and we can test our API using POSTMAN.
GET- Categories List
POST — Add Category
Rest of the API code available on git- repository. You can clone the full project and start working with that.
Related Posts
Mobile App Automation Testing using ‘ESPRESSO’
If you are a Mobile Apps Test Engineer, you cannot overlook the very reliable Google Product i.e. Espresso. Espresso is an automatic UI testing or as we call it “hands…
Mobile App Development and Continuous Delivery – Introduction to Docker (1/7)
DevOps has changed the way application development is done and has significantly influenced mobile app development too! DevOps methodology help bridge the gap between development and operations within an organization,…
Don’t be a data hog! – Designing Android Applications
There are tons of mobile apps out there in the market, each specializing in their own area. There are a plenty of apps built on a single idea, around the…
Teradata and JSON – Monetizing the Internet of Things (IoT)
The prevalent influence of technology has resulted in a widespread use of a variety of devices such as cell phones, sensors, web API’s and browsers. These devices generate huge volume…
6 Technology Trends that Will Redefine Contact Centers
Evolution of technology has improved nearly every sector of our lives. From money transfer to buying clothes, everything is possible with a tap of a finger or click of a…
Real Time Data Ingestion (DiP) – Spark Streaming (co-dev opportunity)
This blog is an extension to that and it focuses on integrating Spark Streaming to Data Ingestion Platform for performing real time data ingestion and visualization. The previous blog DiP (Storm Streaming) showed how…
Excellent pieces. Keep writing such kind of info on your site. Im really impressed by it.
We are a group of volunteers and opening a new scheme in our community. Your site provided us with valuable info to work on. You’ve done a formidable job and our entire community will be thankful to you.
Very nice post. I just stumbled upon your weblog and wished to say that I have really enjoyed surfing around your blog posts. After all I will be subscribing to your feed and I hope you write again soon!
Hey there! I’ve been following your blog for some time now and finally got the bravery to go ahead and give you a shout out from Atascocita Texas! Just wanted to say keep up the excellent work!
Good write-up. I absolutely love this website. Keep it up!
I think you hit a bullyese there fellas!
Nice post Khan.