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

chirag patel
4 min readJul 7, 2018

--

Here I am giving you a short explanation about how you can build NODE Js restful APIs. if you want to read full explanation please visit THIS link.

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

Create a Folder name restApiExample

mkdir restApiExample

Navigate to the root of your newly created folder

cd restApiExample

Now, init node project and Create a package.json file

npm init

Eventually, you will end up with something like this -

https://www.codementor.tech/easy-way-to-build-node-js-restful-apis/

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

Now, create 3 mode folders named controllers, models, routes

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

Your folder structure should look like this now:

https://www.codementor.tech/easy-way-to-build-node-js-restful-apis/

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);
https://www.codementor.tech/easy-way-to-build-node-js-restful-apis/

On your terminal, run

npm run start

output(in your terminal):

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.

After installation, open the userModel.js file and type/copy following code into the file and save. Let’s define the schema.

'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…)

Each route is assigned to different route handler function, which is executed when the route is matched.

We require the controllers to handle function on each of the routes we have defined.

Define Routes-

'use strict';
module.exports = function(app) {
var UsersController = require('../controllers/usersController.js');
// todoList Routes
app.route('/users')
.get(UsersController.listOfUsers)
.post(Users.addUser);
app.route('/users/:userId')
.get(UsersController.getOneUser)
.put(UsersController.updateUser)
.delete(UsersController.deleteUser);
};

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)
res.send(err);
res.json(task);
});
};
exports.addUser = function(req, res) {
var newUser = new Users(req.body);
newUser.save(function(err, user) {
if (err)
res.send(err);
res.json(user);
});
};
exports.getOneUser = function(req, res) {
Users.findById(req.params.userId, function(err, task) {
if (err)
res.send(err);
res.json(task);
});
};
exports.updateUser = function(req, res) {
Users.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, user) {
if (err)
res.send(err);
res.json(user);
});
};
exports.deleteUser = function(req, res) {
Users.remove({
_id: req.params.userId
}, function(err, user) {
if (err)
res.send(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

Your updated server.js-

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;
mongoose.connect('mongodb://localhost/Tododb');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
userRoutes(app);app.get('/',(req,res)=>{
res.send('RESTful API server started on: ' + port)
})
app.listen(port);

The final thing to do

Open your terminal and start MongoDB server

mongod --dbpath <my-db-path>

Once the MongoDB server is running, restart node server.

That’s all Folks CHEERS!!!.

Happy Coding!

--

--

chirag patel
chirag patel

Written by chirag patel

Software Developer , Author @codemetor.tech

No responses yet