Post5

REST API development: Node, Express, Mongo and Mongoose

Posted by

1

The basic purpose of this post is to explain the concept about how we can develop REST API (web services) using node.jsexpress.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.

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.

2

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.

3package.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.

4npm start

Now everything is connected and we can test our API using POSTMAN.

5GET- Categories List

6POST — Add Category

Rest of the API code available on git- repository. You can clone the full project and start working with that.

 

Related Posts

7 comments

  1. 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.

  2. 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!

  3. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *