Posted by : at

Category : web-development   node   mongodb   linux

In this tutorial, We will create a RESTful API Server that gives JSON as output,that can be fetched by any client-side framework like AngularJS, REACTJS or VUEJS etc. or Android or iOS Application.

We will develop the api for a basic blog app. We will be using Node JS for building our API.

Our learning path will be like following

  • Setup NodeJS and MongoDB

  • Create and configure web server(NodeJS + Express) to communicate to database (MongoDB).

  • Build our REST API - CRUD APP (create,read,update and delete).

  • Test our API using POSTMAN App.

Setup NodeJS, NPM and MongoDB

  1. Setup NodeJS

You can use nvm (Node version Manager) to install and use different versions of node.

Install nvm

To check :

$ node -V

$ npm -V

  1. Setup MongoDB

Install mongodb on your system locally or grab remote mongo connection from mlabs

Guide

To check :

$mongod --version

$mongo --version

Create and configure web server(NodeJS + Express) to communicate to database (MongoDB).

Once we have completed the setup process of node and mongodb, we can proceed further to the app development process.

Create a new folder for your app - say “mynodeapp”

$ mkdir mynodeapp

$ cd mynodeapp

Inside your app, we need to init a package.json for our node app.

$ npm init

This will ask some basic information about the app like name, version, description, author , licence etc.

This will create a package.json file for our app.

We need to install some dependencies for our project. Just add the following to your package.json File.

"dependencies": {
    "body-parser": "^1.18.2",
    "cookie-parser": "^1.4.3",
    "express": "^4.16.2",
    "mongoose": "^4.13.1",
    "morgan": "^1.9.0",
    },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "nodemon": "^1.12.1",
  }

Now we need to install this dependencies. We will be using npm package manager to pull this repositories. Just run the following command in your terminal.

$ npm install

This will install all our required dependencies mentioned in our package.json in a node_modules folder.

Now we can get started, in setting up our app.

Our App Folder Structure will be similar to, So create folders and file accordingly :

--- mynodeapp   //Project Directory
    |  
    |
    |---app                            //our app folder
    |   |
    |   |
    |   |--config                      //our app configuration
    |   |      db.js                   //database connection
    |   |--models                      //Our Models
    |   |        user.js               //User model
    |   api.js                         //Our Api Routes
    |---public                         //public assets
    |    |
    |    |--css
    |    |    style.css                //stylesheets
    |    |--js 
    |    |     main.js                  //our main javascript
    |    |--views
    |          index.html
    |---node_modules                   //our app packages
    package.json                       
    server.js                          //Our app server 

server.js

var express = require('express');                    //for our express server 
var logger = require('morgan');                      //for logging 
var bodyParser = require('body-parser');             //for parsing json
var cookieParser = require('cookie-parser');         //for parsing cookies
var mongoose = require('mongoose');                  //mongodb mongoose
var path = require('path');                          //path for folder structure 


var app = express();                                 //Initialize the express app
 
var database = require('./app/config/db.js');        //DB Connection Information

// configuration ===============================================================

mongoose.connect(database.localUrl, {                // Connect to local MongoDB instance.
  useMongoClient: true
}); 

var db = mongoose.connection;                        //Get the default connection

//Bind connection to error event (to get notification of connection errors)

db.on('error', console.error.bind(console, 'MongoDB connection error:'));

app.use(logger('dev'));                              //Morgan for logging

//Cookie-parser parses Cookie header and populate req.cookies with an object keyed by the cookie names
app.use(cookieParser());


app.use(bodyParser.urlencoded({                // parse application/x-www-form-urlencoded    
  'extended': 'true'
}));


app.use(bodyParser.json());                           // parse application/json


var port = process.env.PORT || 4000;                  //Initialize the port for the app to run

//Serving the static files
app.use(express.static(path.join(__dirname, 'public')));

app.use('/assets', express.static(path.join(__dirname, '/node_modules')));

// routes ======================================================================
require('./app/api')(app);                            // configure our routes


app.listen(port);
console.log('App Started at http://localhost:%s', port);


exports = module.exports = app;                      // expose app

Now inside our config folder in - /app/config/db.js

db.js

//Mongodb Database Connection

module.exports = {
  localUrl: 'mongodb://127.0.0.1:27017/mynodeapp'
};

We also need to setup our models, for our project we will build a schema for our user model Inside your /app/models/user.js

user.js

//user model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String,
  email: String
});

module.exports = mongoose.model('User', UserSchema);

Now finally we need to create our api routes to handle the requests Inside your app folder /app/api.js

api.js

var path = require('path');
var User = require('./models/user');

module.exports = function(app){

  // server routes ===========================================================
     // handle things like api calls
     // authentication routes
        app.get('/api',function(req,res){
         res.send('Api home');
        });

        //add users
        app.post('/api/users',function(req,res){
            var user = new User();
            user.name = req.body.name;
            user.email = req.body.email;

            //save the user and check errors
            user.save(function(err){
              if(err){
                res.send(err);
              }
              res.json({
                message: 'User Created Successfully'
              });
            });
        });

          //Get all posts
        app.get('/api/users', function(req,res){
            User.find(function(err, users){
              if(err){
                res.send(err);
              }
              res.json(users);
            });
        });

         //Get a individual User
         app.get('/api/users/:user_id', function(req,res){
           User.findById(req.params.user_id, function(err, user){
               if(err){
                 res.send(err);
               }
               res.json(user);
           });
         });

         //Update a Individual User
         app.put('/api/users/:user_id', function(req,res){
           User.findById(req.params.user_id, function(err, user){
               if(err){
                 res.send(err);
               }
               user.name = req.body.name;
               user.body = req.body.email;

               user.save(function(err){
                  if(err){
                    res.send(err);
                  }
                  res.json({
                    message: 'User Details Successfully Updated'
                  });
               });
           });
         });

         //Delete a user
         app.delete('/api/users/:user_id',function(req,res){
           User.remove({
             _id: req.params.user_id
           },function(err, user){
             if(err){
               res.send(err);
             }
             res.json({
               message: 'User Successfully Deleted'
             })
           });
         });

  // frontend routes (we don't require it yet) =========================================================
      // route to handle all angular requests 
      // app.get('*', function(req, res) {
      //     res.sendFile(path.join(__dirname,'templates', 'index.html'));     
      // });
 //   };


We will be using nodemon to tell the server for any changes while serving our app :

In our package.json we will add the following under our scripts :

start: nodemon server.js

Now we can run the app using :

$ npm run start

The App should be running locally at:

http://localhost:4000

Now we will check the following routes in the postman app

http://localhost:4000/api/users (GET) //Display all users http://localhost:4000/api/users (POST) //Add New Users http://localhost:4000/api/users/:user_id (GET) //Display Individual Users http://localhost:4000/api/users/:user_id (PUT) //Modify Individual Users http://localhost:4000/api/users/:user_id (DELETE) //Delete a User