Monday, January 22, 2018

Build Node.js Mongodb RESTful APIs in 5 Minutes

Rest is the web standards architecture and HTTP Protocol. REST stands for Representational State Transfer and handle the server side of the web application well. That means that the backend is built once and can provide content or data for frontend, mobile, or other server-side apps.

 here will see how to create a RESTful API using Node.js.

Tools:

  • Node.js
  • MongoDB
  • Text editor
  • Postman

Dependencies

Following packages are used
  • body-parser (for parsing incoming requests)
  • express (to make the application run)
  • nodemon (restarting server when changes occur)
  • mongoose (object data modeling to simplify interactions with MongoDB)
  •  

Steps to Create the API

  • Create a Folder name Mongo-Node-Rest-API
  • Navigate to the root of your newly created folder cd Mongo-Node-Rest-API
  • Create a package.json file - npm init


{
  "name": "samplenode",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "rajjaz",
  "license": "ISC"
}

  • Create a file called server.js - touch server.js
  • Create a folder called api Inside this folder called api - mkdir api 
  • create three separate folders called models, routes, and controllers by running mkdir api/controllers api/models api/routes
  • Create todoListController.js in the api/controller folder, todoListRoutes.js in the routes folder, and todoListModel in the model folder - touch api/controllers/todoListController.js api/models/todoListModel.js api/routes/todoListRoutes.js

Server setup

install express and nodmon, express will be used to create the server while nodmon will help us to keep track of changes to our application by watching changed files and automatically restart the server.


npm install --save-dev nodemon

npm install express --save

  • Open the package.json file and add this task to the script
                   "start": "nodemon server.js"
  • Open the server.js file and type/copy the code below into it

var express = require('express'),
  app = express(),
  port = process.env.PORT || 3000;

app.listen(port);

console.log('todo list RESTful API server started on: ' + port);

Install Mongoose

Mongoose is what we will use to interact with a MongoDB(Database) instance.
After installation

npm install mongoose --save
  • Open the todoListModel.js file in your api/models folder and type the following code into the file and save.
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;


var TaskSchema = new Schema({
  name: {
    type: String,
    required: 'Kindly enter the name of the task'
  },
  Created_date: {
    type: Date,
    default: Date.now
  },
  status: {
    type: [{
      type: String,
      enum: ['pending', 'ongoing', 'completed']
    }],
    default: ['pending']
  }
});

module.exports = mongoose.model('Tasks', TaskSchema);

Setting up the routes

  • To do this, open the todoListRoutes.js file in the route folder and paste the code snippet below into
'use strict';
module.exports = function(app) {
  var todoList = require('../controllers/todoListController');

  // todoList Routes
  app.route('/tasks')
    .get(todoList.list_all_tasks)
    .post(todoList.create_a_task);


  app.route('/tasks/:taskId')
    .get(todoList.read_a_task)
    .put(todoList.update_a_task)
    .delete(todoList.delete_a_task);
};

Setting up the controller

Open todoListController.js file with your text editor( Sublime, Atom e.t.c) and let’s deep dive into coding.

In this controller, we would be writing five(5) different functions namely: list_all_tasks, create_a_task, read_a_task, update_a_task, delete_a_task. We will exported each of the functions for us to use in our routes.
Each of these functions uses different mongoose methods such as find, findById, findOneAndUpdate, save and remove.

'use strict';


var mongoose = require('mongoose'),
  Task = mongoose.model('Tasks');

exports.list_all_tasks = function(req, res) {
  Task.find({}, function(err, task) {
    if (err)
      res.send(err);
    res.json(task);
  });
};




exports.create_a_task = function(req, res) {
  var new_task = new Task(req.body);
  new_task.save(function(err, task) {
    if (err)
      res.send(err);
    res.json(task);
  });
};


exports.read_a_task = function(req, res) {
  Task.findById(req.params.taskId, function(err, task) {
    if (err)
      res.send(err);
    res.json(task);
  });
};


exports.update_a_task = function(req, res) {
  Task.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, task) {
    if (err)
      res.send(err);
    res.json(task);
  });
};


exports.delete_a_task = function(req, res) {


  Task.remove({
    _id: req.params.taskId
  }, function(err, task) {
    if (err)
      res.send(err);
    res.json({ message: 'Task successfully deleted' });
  });
};
  • Open the server.js file created awhile ago and follow the following steps to put everything together.
var express = require('express'),
  app = express(),
  port = process.env.PORT || 3000,
  mongoose = require('mongoose'),
  Task = require('./api/models/todoListModel'), //created model loading here
  bodyParser = require('body-parser');
  
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb'); 


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


var routes = require('./api/routes/todoListRoutes'); //importing route
routes(app); //register the route


app.listen(port);


console.log('todo list RESTful API server started on: ' + port);

Start MongoDB Server

  • If you laready have the Mongodb setup open your terminal and run mongod
  • Else create the TB called Tododb

sudo apt install mongodb-server
mongo
use Tododb;
If you get the error message like mentioned below please do the below steps to overcone the issue.

*********************************************************************
 ERROR: dbpath (/data/db) does not exist.
 Create this directory or give existing directory in --dbpath.
 See http://dochub.mongodb.org/core/startingandstoppingmongo
*********************************************************************

sudo mkdir -p /data/db/
sudo chown `id -u` /data/db

Testing The API

 POST/
















GET/

















GET /ID

















Find the Full code here

References
  • https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd

2 comments: