Create your own REST API using node.js and Mongo (Part 4 – Final part ) Using http requests and testing our API with pos

Hi there, welcome to the final part of the series:”Create your own REST API using node.js and Mongo”. In this final part of the series,we will put everything we learned together to create a fully functional REST API.

It is important that we structure our project. I am going to do this by doing the following:

  1. Delete or remove the parcel.js file (we are not going to use it in this final part).
  2. In the root folder of your project create a new file called “server.js”
  3. Create a new folder in the root of your project and call it “app”.
  4. Inside the “app” folder create 3 new folders and name them “models”,”controllers”, “routes” respectively.
  5. Inside your models folder create a file called “parcelmodel.js”
  6. Inside your controllers folder create a file called “parcelcontroller.js”
  7. Inside your routes folder create a file called “parcelroute.js”

Your file structure should now be looking  something like this:

app

-models

–parcelmodel.js

-controllers

–parcelcontroller.js

-routes

–parcelroute.js

node_modules

package.json

server.json

Now that we have our project folder structured we need to install the following npm packages:

  • Install Express

Because we want to create a REST API we will make use of Express to help us with routes, handling the requests and views. Express also implements the popular MVC framework into our application making things much easier for developers.

$ npm install express –save

  •  Install body-parser

$ npm install –save body-parser

1.Setting up the server

var express = require('express');
var app = express();
var port  = 3000;

app.listen(port);
console.log('Parcel app server is started on port: ' + port);

Inside command prompt type:

$ node server.js

The following should be displayed inside of the command window:

serverrunning.JPG

2. Setting up our parcel model

Inside your parcelmodel.js file type the following:

//Load mongoose to allow interaction with our database
var mongoose = require ('mongoose');

//Create/Use database called ParcelTest
var connection = mongoose.connect('mongodb://localhost/ParcelTest');

//Create database schema called ParcelSchema
var ParcelSchema = new mongoose.Schema({
 itemname : String,
 collected : Boolean,
 collected_at : { type: Date, default: Date.now }
});

module.exports = mongoose.model('Parcel', ParcelSchema);

What happens here is that we load mongoose that allows us to interact with our database. We now create a model of how our collection should look like. The Parcel table contains an itemname of type String, a collected field of type Boolean and a collected_at field of type Date.

3. Setting up our routes

Inside of your parcelroute.js file type the following code:

module.exports = function(app) {
 var parcelList = require('../controllers/parcelcontroller');

//Routes
 app.route('/parcels')
 .get(parcelList.list_all)
 .post(parcelList.create_parcel);

 //Routes with id parameter
 app.route('/parcels/:parcelId')
 .get(parcelList.read_parcel)
 .put(parcelList.update_parcel)
 .delete(parcelList.delete_parcel);
};

These routes specify how an application responds to a request from the client. Refer to the first part of this series for the explanation of GET, PUT, POST and DELETE HTTP requests which we used in our parcelroute.js file as shown above.

4. Adding functions to our controller

Inside of our parcelcontroller.js file we will write the functions that we call in the parcelroute.js file namely:

list_all

create_parcel

read_parcel

update_parcel

delete_parcel

Inside your parcelcontroller.js file enter the following code:

'use strict';

//Load mongoose to allow interaction with our database
var mongoose = require('mongoose'),
 Parcel = mongoose.model('Parcel');


//Get all parcels and display them
exports.list_all = function(req, res) {
 Parcel.find({}, function(err, parcel) {
 if (err)
 res.send(err);
 res.json(parcel);
 });
};

//Create a new parcel and save it to our database
exports.create_parcel = function(req, res) {
 var new_parcel = new Parcel(req.body);
 new_parcel.save(function(err, parcel) {
 if (err)
 res.send(err);
 res.json(parcel);
 });
};

//Read a parcel from database by id
exports.read_parcel = function(req, res) {
 Parcel.findById(req.params.parcelId, function(err, parcel) {
 if (err)
 res.send(err);
 res.json(parcel);
 });
};

//Update a parcel by id
exports.update_parcel = function(req, res) {
 Parcel.findOneAndUpdate(req.params.parcelId, req.body, {new: true}, function(err, parcel) {
 if (err)
 res.send(err);
 res.json(parcel);
 });
};

//Delete parcel by id
exports.delete_parcel = function(req, res) {
 Parcel.remove({
 _id: req.params.parcelId
 }, function(err, parcel) {
 if (err)
 res.send(err);
 res.json({ message: 'Parcel successfully deleted' });
 });
};

5. Create the database connection and register the routes

We have now successfully created our parcel model, controller and our routes. Now it is time to set up our connection with our database and to register our routes with our web server. This is done by adding the following to your server.js file:

var express = require('express');
var app = express();
var port = 3000;

//Load mongoose to allow interaction with our database
var mongoose = require ('mongoose'),
 Parcel = require('./app/models/parcelmodel'),
 bodyParser = require('body-parser');

//Load mongoose to allow interaction with our database
var mongoose = require ('mongoose');

//To use mongoose async operations
mongoose.Promise = global.Promise;

//Create/Use database called ParcelTest
var connection = mongoose.createConnection('mongodb://localhost/ParcelTest');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var routes = require('./app/routes/parcelroute');
routes(app);

app.listen(port);
console.log('Parcel app server is started on port: ' + port);

6. Testing our API

Great work, everything is now set up and we can begin to test our API with Postman.

Ensure that your MongoDB server is running. Refer to part 1 of the series.

When your mongo server is running, ensure that your node server is also running. Do this by using the command prompt and running your server.js file:

$ node server.js

With both servers running open your Postman application. In the URL Request input box type the following:

http://localhost:8080/parcels

and click on “Send”.

postman.JPG

 

You should see something similar to this as output:

[
 {
 "_id": "58b92eba3cedd3641e101b59",
 "itemname": "Flowers",
 "collected": false,
 "__v": 0,
 "collected_at": "2017-03-03T08:52:10.361Z"
 }
]

 

To test the other routes that has an id as a parameter add the id to the url as I have done here:

postmanbyid.JPG

That’s it, we have now created our very own REST API using Node.js and Mongo. Thank you for reading. Feel free to ask questions in the comments.

 

 

 

 

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s