Build Secure Node.js, MongoDB, Express RESTful API From Scratch

By Digamber Rawat Last updated on
This is a step by step tutorial on building secure Node.js, MongoDB, Express RESTful API from scratch, In this tutorial, we will learn how to create a secure RESTful API using Node, MongoDB, and Express JS in 10 minutes. Creating web, mobile, or any software application using REST API is a better way to manage the scalability and performance of the web application. APIs are reusable code and considered best for scalability.

We all use various softwares, web, and mobile applications to make our life easy. We browse the internet without knowing the harm it could give to us, and it also doesn’t matter whether you are a software developer or not. Mostly every software application work on API pattern.

API (Application Programming Interface) is “a set of subroutine definitions, communication protocols, and tools for building software. … Good APIs makes it easier to develop a computer program by providing all the building blocks, which are then put together by the programmer.”

Understand REST in Software Engineering

REST stands for Representational State Transfer, and it is used to fetch and manage the data using various stateless services. CRUD (Create, Read, Update, Delete) operations are the internal part of the HTTP protocol, and these operations allow us to manipulate the data on the server through RESTful APIs.

HTTP Services Types:

Property Detail
POST Create data or individual item
GET Get an item or single data
PUT Create or replace data
PATCH Update data
DELETE Delete a resource

We are going to build RESTful APIs for school management system based on the CRUD operation pattern. We will create the REST endpoints with Node, Express, and MongoDB.

Step 1: Getting Started

In order to work on this tutorial you must have Node.js setup in your system, checkout how To install Node JS in your system?

Then, you must have MongoDB installed in your system, you can visit www.mongodb.com website to install mongoDB. Follow this tutorial install MongoDB on MacOS in 5 minutes.

Step 2: Node.js RESTful API Project Setup

For this tutorial, I will be using MacOS and visual studio code editor; however, you can choose any tool to get started.

In the first step, create a project folder, where will keep all our code. Enter the below command in the terminal to create the project folder and enter into it.

Node JS REST API project name: node-express-rest-api

mkdir node-express-rest-api && cd node-express-rest-api

Run npm command to initialize the project via Node js, as soon as you enter the command. You will be asked following questions along with entry point we are using server.js but you can name it anything you want:

npm init
name: (node-express-rest-api)
version: (0.0.0)
description: A node rest api project.
entry point: (index.js)
test command:
git repository: (https://github.com/SinghDigamber/node-express-rest-api)
keywords:
author: Digamber Rawat <digamber@positronx.io> (https://positronx.io)
license: (ISC)

In next step, we are installing required npm modules to create RESTful APIs.

npm install --save express mongoose cors body-parser

Next, install nodemon module. It’ll save us from restarting the server every-time we make the changes in the project. It observes changes in project files and modules and restarts the server as soon as any change occurs.

npm install nodemon --save-dev

Final package.json File

{
  "name": "node-express-rest-api",
  "version": "1.0.0",
  "description": "Build Secure Node.js, MongoDB, Express RESTful API From Scratch",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/SinghDigamber/node-express-rest-api.git"
  },
  "keywords": [],
  "author": "Digamber Rawat",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/SinghDigamber/node-express-rest-api/issues"
  },
  "homepage": "https://github.com/SinghDigamber/node-express-rest-api#readme",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mongoose": "^5.6.0"
  },
  "devDependencies": {
    "nodemon": "^1.19.1"
  }
}

Step 3: MongoDB Set up for REST API Tutorial

In this step, we are going to keep database settings using Mongoose. Create a folder in the root of your project and name it db. Create a file by the name of database.js in the db folder. In this file we will keep mongoDB settings, it will help us in making the database connection in MEAN stack app.

Enter the command in the terminal:

mkdir db

Go inside the folder:

cd db

Create database.js file:

touch database.js

Go to db > database.js file and add the following code:

module.exports = {
  db: 'mongodb://localhost:27017/restapi'
}

Here, mongoDB works on port 27017 locally, and restapi is the database name.

Step 4: Creating Student Schema Module

We have already installed Mongoose from NPM library to make the mongoDB connection. Mongoose is based on object data modeling (ODM). It helps in creating the data model using the schema pattern.

Enter the command to create the folder structure for student schema module from the root of your project folder:

mkdir model && cd model && touch student.model.js

Go to model > student.model.js file and add the following code:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let studentSchema = new Schema({
    name: {
        type: String
    },
    email: {
        type: String
    },
    dob: {
        type: Date
    }
}, {
    collection: 'students'
})

module.exports = mongoose.model('StudentSchema', studentSchema)

Step 5: Build RESTful API with Express & Node JS

Next, we will build RESTful APIs with Express js in Node js app. First, we’ll create routes folder and create a student.routes.js file in it.

Run command to build the routes folder and student.routes.js file.

mkdir routes && cd routes && touch student.route.js

Then, in the student.route.js file, we will import express js and student schema model. We can use the express js method to build robust and secure RESTful APIs, as mentioned below:

const express = require('express');
const app = express();

// Express route
const studentExpressRoute = express.Router();

// User schema
let StudentSchema = require('../model/student.model');

// Get users
studentExpressRoute.route('/').get((req, res) => {
    StudentSchema.find((error, data) => {
        if (error) {
            return next(error)
        } else {
            res.json(data)
        }
    })
})

// Create user
studentExpressRoute.route('/create-student').post((req, res, next) => {
    StudentSchema.create(req.body, (error, data) => {
        if (error) {
            return next(error)
        } else {
            res.json(data)
        }
    })
});


// Get single user
studentExpressRoute.route('/get-student/:id').get((req, res) => {
    StudentSchema.findById(req.params.id, (error, data) => {
        if (error) {
            return next(error)
        } else {
            res.json(data)
        }
    })
})


// Update user
studentExpressRoute.route('/update-student/:id').put((req, res, next) => {
    StudentSchema.findByIdAndUpdate(req.params.id, {
        $set: req.body
    }, (error, data) => {
        if (error) {
            return next(error);
        } else {
            res.json(data)
            console.log('Student successfully updated!')
        }
    })
})

// Delete student
studentExpressRoute.route('/remove-student/:id').delete((req, res, next) => {
    StudentSchema.findByIdAndRemove(req.params.id, (error, data) => {
        if (error) {
            return next(error);
        } else {
            res.status(200).json({
                msg: data
            })
        }
    })
})

module.exports = studentExpressRoute;

Step 6: Node App Server Settings

First, create a server.js file in the root of your project. In this file, we will keep our server settings. Add the given below code in server js file:

let express = require('express'),
    path = require('path'),
    mongoose = require('mongoose'),
    cors = require('cors'),
    bodyParser = require('body-parser'),
    dbConfig = require('./db/database');


// Connecting mongoDB
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, {
    useNewUrlParser: true
}).then(() => {
        console.log('Database connected')
    },
    error => {
        console.log('Database could not be connected : ' + error)
    }
)

// Setting up express
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cors());

// Api root
const userRoute = require('./routes/student.route')
app.use('/endpoint', userRoute)

// Create port
const port = process.env.PORT || 8080;

// Conectting port
const server = app.listen(port, () => {
    console.log('Port connected to: ' + port)
})

// Find 404 and hand over to error handler
app.use((req, res, next) => {
    next(createError(404));
});

// Index Route
app.get('/', (req, res) => {
    res.send('invaild endpoint');
});

// error handler
app.use(function (err, req, res, next) {
    console.error(err.message);
    if (!err.statusCode) err.statusCode = 500;
    res.status(err.statusCode).send(err.message);
});

// Static build location
app.use(express.static(path.join(__dirname, 'dist')));

As you can see in above file, we have performed the following tasks:

  • MongoDB connection
  • Express JS settings
  • Defined REST API root
  • CreateD PORT for Node app
  • Express.js route error handling
  • Setting up build location via express

Now, we have successfully produced Node, Express and MongoDB RESTful API with the following structure:

  • name
  • email
  • dob (date of birth)

Given below table includes REST API’s and their respective methods:

API Method Endpoint
POST endpoint/create-student
GET endpoint/ (list students)
GET endpoint/get-student/:id (get student from students list)
PUT endpoint/update-student/:id (update specific student data)
DELETE endpoint/remove-student/:id (delete specific student data)

Step 7: Testing Express JS REST API

In this last step, we are going to test our RESTful APIs locally. Follow the given below process to get started with testing.

Express.js REST API URL: http://localhost:8080/endpoint

To test REST API locally, run the following command in the terminal.

curl -i -H "Accept: application/json" localhost:8080/endpoint

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 2
ETag: W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"
Date: Thu, 20 Jun 2019 13:17:35 GMT
Connection: keep-alive

Step 8: Testing Node JS RESTful API with Postman

In order to test REST API in postman you need to have installed Postman in your machine. You can visit here to download the Postman API testing tool.

Once you are done downloading Postman then open it and select the HTTP method from the top left part. Then enter the REST API in the search bar and if you are getting the response similar as in the screenshot below, it means our REST API is working.

Node REST API

You can also test your other REST APIs in Postman, finally we are done creating secure RESTful API with Node.js, MongoDB and Express JS from scratch. You can click below to checkout the GitHub repo for this project.

GitHub Repo

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.