Easy way to Build Node JS RESTful APIs — codementor.tech

Tools needed:

Get started

Download and Install Node.js & MongoDB

Kindley run following commands to check NPM and MongoDB installed on your machine:

npm -v
mongo --version
mkdir restApiExample
cd restApiExample
npm init

Eventually, you will end up with something like this -


Create a file called server.js

In this file, we will be writing protocols to create our server.

touch server.js

Create a folder called api

Inside this folder name “api” we will have everything to create server i.e API Controller, Models, Routes, etc.

mkdir api
mkdir api/controllers api/models api/routes

Create usersController.js in the api/controllers folder, usersRoutes.js in the api/routes folder and userModel.js in the api/models folder -

touch api/controllers/usersController.js api/routes/usersRoutes.js api/models/userModel.js

Server setup

Let’s install express and nodemon, express will be used to create server while nodemon will help to keep track of changes to the application by watching changed files and automatically restart the server.

npm install --save-dev nodemonnpm install --save express

Now, Open the server.js file and type/copy the following code into it

var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port);console.log('RESTful API server started on: ' + port);
npm run start
RESTful API server started on: 3030

Setting up the Schema

Let’s install mongoose first -

npm install --save mongoose

Why Mongoose?

Mongoose is node package which is used to interact with MongoDB instance.

'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name: {
type: String,
required: 'Kindly enter the name'
created_date: {
type: Date,
default: Date.now
type: {
type: [{
type: String,
enum: ['admin', 'student', 'teacher']
default: ['student']
module.exports = mongoose.model('Users', UserSchema);

Setting up the Routes

Routing refers to determining how an application will respond to a client request for a specific endpoint, which is HTTP request method(GET, PUT, POST, DELETE, etc…)

'use strict';
module.exports = function(app) {
var UsersController = require('../controllers/usersController.js');
// todoList Routes

Setting up the controller

Define all the function in usersController.js which are assigned to each of the usersRoutes.

'use strict';var mongoose = require('mongoose'),
Users = require('../models/userModel');
exports.allUsers = function(req, res) {
Users.find({}, function(err, task) {
if (err)
exports.addUser = function(req, res) {
var newUser = new Users(req.body);
newUser.save(function(err, user) {
if (err)
exports.getOneUser = function(req, res) {
Users.findById(req.params.userId, function(err, task) {
if (err)
exports.updateUser = function(req, res) {
Users.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, user) {
if (err)
exports.deleteUser = function(req, res) {
_id: req.params.userId
}, function(err, user) {
if (err)
res.json({ message: 'Task successfully deleted' });

Almost Done,

Open server.js file

  • connect with database i.e. MongoDB by adding a URL to the mongoose instance connection
  • install bodyParser to parse the API request data
var express = require('express'),
app = express(),
port = process.env.PORT || 3030,
mongoose = require('mongoose'),
bodyParser = require('body-parser')
userRoutes = require('./api/routes/usersRoutes');
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
res.send('RESTful API server started on: ' + port)

The final thing to do

Open your terminal and start MongoDB server

mongod --dbpath <my-db-path>



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store