Building a REST API in NodeJS, Express and MongoDB

REST stands for Representational state transfer.

A REST API defines a set of functions which developers can perform requests and receive responses via HTTP protocol such as GET, POST, DELETE, PUT, PATCH.

A Real World Example: Facebook  provides a REST API which you can query to get the number likes, you can provide a search query like page name and it will return the results in JSON format.

But here, we will see how can we build a REST API using Node JS and with the help of Mongo DB.

1. Sending a request to server and getting back data in JSON – A basic example below

App.js

  1. var express = require(‘express’);
  2. var app = express();
  3. //port number specification
  4. var port = process.env.port || 3000;
  5. bookRouter = require(‘./routes/bookRoutes’)(Book);
  6. app.use(‘/api’, bookRouter);
  7. //listening to a port
  8. app.listen(port, function(){
  9.   console.log(‘Running on port’ +port);
  10. });

bookRoutes.js

  1. var express = require(‘express’);
  2. var routes = function(Book){
  3. var bookRouter = express.Router();
  4. bookRouter.route(‘/Books’)
  5. .get(function(req, res){
  6.   var resJSON = {hello:‘This is my app’};
  7.     res.json(resJSON);
  8. });
  9.   return bookRouter;
  10. };
  11. module.exports = routes;

Now When we compile nodemon app.js in Command Prompt

And send request to http://localhost:3000/api/Books

Here is the result:

There it is getting the JSON response on a simple GET request.

2. Building a custom API – A book record API which fetches the book title, author name, and genre.

a. Building a Database of book record in Mongo DB.

I have used a free 500MB sandbox plan from mlab.com to build our DB in Mongo.

In Mongo DB the data is stored in BSON format as documents.

To know about the Mongo DB setup visit my previous post here

Create a collection and name it as shown:

Now add documents(data) in JSON format

  1. {
  2.     “title”: “Rich Dad Poor Dad”,
  3.     “author”: “Robert Kiyosaki”,
  4.    “genre”: “finance”
  5. },
  6. {
  7.    “title”: “The Alchemist”,
  8.     “author”: “Paulo Coelho”,
  9.     “genre”: “fiction”
  10. },
  11. {
  12.     “title”: “Hit Refresh”,
  13.     “author”: “Satya nadella”,
  14.     “genre”: “Biography”
  15. }

n ID will assigned automatically to your each document.

Now how to fetch the data from the DB by sending API request?

Here is how:

Setup the following file structure:

app.js

  1. var express = require(‘express’);
  2. var mongoose = require(‘mongoose’);
  3. var app = express();
  4. //port number specification
  5. var port = process.env.port || 3000;
  6. //MongoDB connection
  7. var db = mongoose.connect(‘mongodb://sarthakdb:pwd@ds243345.mlab.com:43345/diary’);
  8. //Model file code required
  9. var Book = require(‘./models/bookModel’);
  10. bookRouter = require(‘./routes/bookRoutes’)(Book);
  11. app.use(‘/api’, bookRouter);
  12. //listening to a port
  13. app.listen(port, function(){
  14.     console.log(‘Running on port’ +port);
  15. });

../models/bookModel.js

  1. var mongoose = require(‘mongoose’);
  2. //var Schema = mongoose.Schema();
  3. var bookModel = mongoose.Schema({
  4.   title:{
  5.     type:String
  6.   },
  7.   author:{type:String},
  8.   genre:{type:String},
  9. });
  10. module.exports = mongoose.model(‘Book’, bookModel);

for modular coding we have setup the routes file for clean routing of modules.

GET Requests to the API

../routes/bookRoutes.js

The below code sends a GET requests and fetches all the data available in the DB(just like SELECT all QUERY in SQL)

  1. var express = require(‘express’);
  2. var routes = function(Book){
  3.   var bookRouter = express.Router();
  4. bookRouter.route(‘/Books’)
  5. .get(function(req, res){
  6.   Book.find(function(err, books){
  7.     if(err)
  8.     res.status(500).send(err);
  9.    //console.log(err);
  10.     else
  11.       res.json(books);
  12.   });
  13. });
  14.   return bookRouter;
  15. };
  16. module.exports = routes;

Compile the nodemon app.js and send request to http://localhost:3000/api/Books

and there it is, our GET request result

Now since our result can fetched directly from DB by sending request to the API we can query the request based on different parameters… like genre, authors, id, title…

here is how,

Just change few lines in bookRoutes.js

  1. var express = require(‘express’);
  2. var routes = function(Book){
  3.   var bookRouter = express.Router();
  4. //filter GET like http://localhost:3000/api/books?genre=fiction
  5. bookRouter.route(‘/Books’)
  6. .get(function(req, res){
  7.   var query = {};
  8.     if(req.query.genre){
  9.       query.genre = req.query.genre;
  10.     }
  11.   Book.find(query, function(err, books){
  12.     if(err)
  13.     res.status(500).send(err);
  14.     else
  15.       res.json(books);
  16.   });
  17. });
  18. return bookRouter;
  19. };
  20. module.exports = routes;

filter GET as http://localhost:3000/api/books?genre=fiction

filter GET request by ID http://localhost:3000/api/idnumber

 


POST Requests to the API

For POST request we have add the body parser package node js.

app.js

  1. var express = require(‘express’);
  2. var mongoose = require(‘mongoose’);
  3. //body parser for POST request
  4. var bodyParser = require(‘body-parser’);
  5. var app = express();
  6. //port number specification
  7. var port = process.env.port || 3000;
  8. //MongoDB connection
  9. var db = mongoose.connect(‘mongodb://sarthakdb:pwd@ds243345.mlab.com:43345/diary’);
  10. //Model file code required
  11. var Book = require(‘./models/bookModel’);
  12. //URL POST request using body parser
  13. app.use(bodyParser.urlencoded({extended: true}));
  14. app.use(bodyParser.json());
  15. bookRouter = require(‘./routes/bookRoutes’)(Book);
  16. app.use(‘/api’, bookRouter);
  17. //run as localhost:3000/
  18. app.get(‘/’, function(req, res){
  19. res.send(‘hello ‘);
  20. });
  21. //listening to a port
  22. app.listen(port, function(){
  23.   console.log(‘Running on port’ +port);
  24. });

bookRoutes.js

  1. var express = require(‘express’);
  2. var routes = function(Book){
  3. var bookRouter = express.Router();
  4. bookRouter.route(‘/Books’)
  5. .post(function(req, res){
  6.   var book = new Book(req.body);
  7.   book.save();
  8.   res.status(201).send(book);
  9. });
  10.   return bookRouter;
  11. };
  12. module.exports = routes;

Now To test our request we have download POSTMAN chrome extension app.

Sending GET request in POSTMAN app to check…

 


Now GET seems to work fine, now send i a POST request to add one more Book Data

like

  1. {
  2.     “title”: “Harry Potter”,
  3.     “author”: “J.K Rowling”,
  4.     “genre”: “Science fiction”
  5. }


check it in our Mongo DB if its updated
 

 

yes it is the 4th document is added..

again sending a GET to verify


Similarly we can update and Delete using PUT and DELETE using below code:

  1. var express = require(‘express’);
  2. var routes = function(Book){
  3.   var bookRouter = express.Router();
  4. bookRouter.route(‘/Books’)
  5. .post(function(req, res){
  6.   var book = new Book(req.body);
  7.   book.save();
  8.   res.status(201).send(book);
  9. })
  10. .put(function(req, res){
  11.   Book.findById(req.params.bookid, function(err, books){
  12.     if(err)
  13.     res.status(500).send(err);
  14.     else
  15.       books.title = req.body.title;
  16.     books.author = req.body.author;
  17.     books.genre = req.body.genre;
  18.     books.save();
  19.       res.json(books);
  20.   });
  21. })
  22. .delete(function(req, res){
  23.   Book.findById(req.params.bookid, function(err, books){
  24.       req.books.remove(function(err){
  25.         if(err)
  26.           res.status(500).send(err);
  27.         else{
  28.         res.status(204).send(‘Removed!’);
  29.       }
  30.   });
  31.   });
  32. });
  33.   return bookRouter;
  34. };
  35. module.exports = routes;

Hence the basic API is ready using Node js…we can make it more feature like adding Hypermedia and connecting it with other APIs.

For DB we can use SQL also.

Advertisement

3 thoughts on “Building a REST API in NodeJS, Express and 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 )

Facebook photo

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

Connecting to %s