Building a REST API using Node, 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.  
  5.   title:{
  6.     type:String
  7.   },
  8.   author:{type:String},
  9.   genre:{type:String},
  10.  
  11. });
  12. 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.  
  4.   var bookRouter = express.Router();
  5. bookRouter.route('/Books')
  6. .get(function(req, res){
  7.   Book.find(function(err, books){
  8.     if(err)
  9.     res.status(500).send(err);
  10.    //console.log(err);
  11.     else
  12.       res.json(books);
  13.   });
  14.  
  15. });
  16.   return bookRouter;
  17. };
  18. 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.  
  4.   var bookRouter = express.Router();
  5. //filter GET like http://localhost:3000/api/books?genre=fiction
  6. bookRouter.route('/Books')
  7. .get(function(req, res){
  8.   var query = {};
  9.     if(req.query.genre){
  10.       query.genre = req.query.genre;
  11.     }
  12.   Book.find(query, function(err, books){
  13.    
  14.    
  15.     if(err)
  16.     res.status(500).send(err);
  17.    
  18.     else
  19.       res.json(books);
  20.   });
  21.  
  22. });
  23. return bookRouter;
  24. };
  25. 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.  
  4. var bookRouter = express.Router();
  5. bookRouter.route('/Books')
  6. .post(function(req, res){
  7.  
  8.   var book = new Book(req.body);
  9.   book.save();
  10.   res.status(201).send(book);
  11. });
  12.   return bookRouter;
  13. };
  14. 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.  
  4.   var bookRouter = express.Router();
  5. bookRouter.route('/Books')
  6. .post(function(req, res){
  7.  
  8.   var book = new Book(req.body);
  9.   book.save();
  10.   res.status(201).send(book);
  11. })
  12. .put(function(req, res){
  13.   Book.findById(req.params.bookid, function(err, books){
  14.    
  15.    
  16.     if(err)
  17.     res.status(500).send(err);
  18.    
  19.     else
  20.       books.title = req.body.title;
  21.     books.author = req.body.author;
  22.     books.genre = req.body.genre;
  23.     books.save();
  24.       res.json(books);
  25.   });
  26.  
  27. })
  28. .delete(function(req, res){
  29.   Book.findById(req.params.bookid, function(err, books){
  30.    
  31.    
  32.    
  33.       req.books.remove(function(err){
  34.         if(err)
  35.           res.status(500).send(err);
  36.        
  37.         else{
  38.         res.status(204).send('Removed!');
  39.       }
  40.      
  41.   });
  42.     
  43.   });
  44.  
  45. });
  46.   return bookRouter;
  47. };
  48. 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.



Comments

Popular posts from this blog

AWS LEX - Developing a Simple Chat Bot

Connecting Mongo DB with NodeJS

BUILDING A CHAT BOT USING MICROSOFT AZURE BOT SERVICE & LUIS