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
- var express = require('express');
- var app = express();
- //port number specification
- var port = process.env.port || 3000;
- bookRouter = require('./routes/bookRoutes')(Book);
- app.use('/api', bookRouter);
- //listening to a port
- app.listen(port, function(){
- console.log('Running on port' +port);
- });
bookRoutes.js
- var express = require('express');
- var routes = function(Book){
- var bookRouter = express.Router();
- bookRouter.route('/Books')
- .get(function(req, res){
- var resJSON = {hello:'This is my app'};
- res.json(resJSON);
- });
- return bookRouter;
- };
- 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.
Create a collection and name it as shown:
Now add documents(data) in JSON format
- {
- "title": "Rich Dad Poor Dad",
- "author": "Robert Kiyosaki",
- "genre": "finance"
- },
- {
- "title": "The Alchemist",
- "author": "Paulo Coelho",
- "genre": "fiction"
- },
- {
- "title": "Hit Refresh",
- "author": "Satya nadella",
- "genre": "Biography"
- }
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
- var express = require('express');
- var mongoose = require('mongoose');
- var app = express();
- //port number specification
- var port = process.env.port || 3000;
- //MongoDB connection
- var db = mongoose.connect('mongodb://sarthakdb:pwd@ds243345.mlab.com:43345/diary');
- //Model file code required
- var Book = require('./models/bookModel');
- bookRouter = require('./routes/bookRoutes')(Book);
- app.use('/api', bookRouter);
- //listening to a port
- app.listen(port, function(){
- console.log('Running on port' +port);
- });
../models/bookModel.js
- var mongoose = require('mongoose');
- //var Schema = mongoose.Schema();
- var bookModel = mongoose.Schema({
- title:{
- type:String
- },
- author:{type:String},
- genre:{type:String},
- });
- 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)
- var express = require('express');
- var routes = function(Book){
- var bookRouter = express.Router();
- bookRouter.route('/Books')
- .get(function(req, res){
- Book.find(function(err, books){
- if(err)
- res.status(500).send(err);
- //console.log(err);
- else
- res.json(books);
- });
- });
- return bookRouter;
- };
- 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
- var express = require('express');
- var routes = function(Book){
- var bookRouter = express.Router();
- //filter GET like http://localhost:3000/api/books?genre=fiction
- bookRouter.route('/Books')
- .get(function(req, res){
- var query = {};
- if(req.query.genre){
- query.genre = req.query.genre;
- }
- Book.find(query, function(err, books){
- if(err)
- res.status(500).send(err);
- else
- res.json(books);
- });
- });
- return bookRouter;
- };
- 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
- var express = require('express');
- var mongoose = require('mongoose');
- //body parser for POST request
- var bodyParser = require('body-parser');
- var app = express();
- //port number specification
- var port = process.env.port || 3000;
- //MongoDB connection
- var db = mongoose.connect('mongodb://sarthakdb:pwd@ds243345.mlab.com:43345/diary');
- //Model file code required
- var Book = require('./models/bookModel');
- //URL POST request using body parser
- app.use(bodyParser.urlencoded({extended: true}));
- app.use(bodyParser.json());
- bookRouter = require('./routes/bookRoutes')(Book);
- app.use('/api', bookRouter);
- //run as localhost:3000/
- app.get('/', function(req, res){
- res.send('hello ');
- });
- //listening to a port
- app.listen(port, function(){
- console.log('Running on port' +port);
- });
bookRoutes.js
- var express = require('express');
- var routes = function(Book){
- var bookRouter = express.Router();
- bookRouter.route('/Books')
- .post(function(req, res){
- var book = new Book(req.body);
- book.save();
- res.status(201).send(book);
- });
- return bookRouter;
- };
- 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
- {
- "title": "Harry Potter",
- "author": "J.K Rowling",
- "genre": "Science fiction"
- }
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:
- var express = require('express');
- var routes = function(Book){
- var bookRouter = express.Router();
- bookRouter.route('/Books')
- .post(function(req, res){
- var book = new Book(req.body);
- book.save();
- res.status(201).send(book);
- })
- .put(function(req, res){
- Book.findById(req.params.bookid, function(err, books){
- if(err)
- res.status(500).send(err);
- else
- books.title = req.body.title;
- books.author = req.body.author;
- books.genre = req.body.genre;
- books.save();
- res.json(books);
- });
- })
- .delete(function(req, res){
- Book.findById(req.params.bookid, function(err, books){
- req.books.remove(function(err){
- if(err)
- res.status(500).send(err);
- else{
- res.status(204).send('Removed!');
- }
- });
- });
- });
- return bookRouter;
- };
- 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
Post a Comment