How to Create REST API Easily using Node.js, Express.js, Mongoose.js and MongoDB

by Didin J. on Feb 19, 2017 How to Create REST API Easily using Node.js, Express.js, Mongoose.js and MongoDB

How to Create REST API using Node.js, Express.js, Mongoose.js and MongoDB with an easy and effective way.

Node.js, Express.js, Mongoose.js and MongoDB is the great combination for building easy and fast REST API. You will see how fast that combination than other existing frameworks because of Node.js is a packaged compilation of Google’s V8 JavaScript engine and it works on non-blocking and event-driven I/O. Express.js is javascript web server that has complete function of web development including REST API.

Before we begin, make sure you have installed all tools that required.

In this tutorial, we will work using Terminal and Atom as the text editor. For Windows user, you can work using Node.js command line. We started this Node.js, Express.js, Mongoose.js and MongoDB tutorial from scratch and then continue a quicker way using Node-Restful library. Let's begin.


1. Create Express.js Project and Install Required Modules

Open your terminal or node command line the go to your projects folder. First, install express generator using this command.

sudo npm install express-generator -g

Next, create an Express.js app using this command.

express node-rest-api -e
This will create Express.js project with the EJS view instead of Jade view template because using '-e' parameter. Next, go to newly created project folder then install node modules.
cd node-rest-api && npm install
Run the server by this command.
npm start
You will see the log like this in the terminal.
> [email protected] start /Users/didin/Documents/NodeApps/node-rest-api
> node ./bin/www
Open your browser then pointing to 'localhost:3000', if you see like the image below then your server is ready.

Node.js, Express.js, Mongoose.js and MongoDB - Express Home


2. Add Mongoose.js Module as ORM for MongoDB

Stop node by push CTRL+C on the keyboard. Type this command to install Mongoose.js module.

npm install mongoose --save
Before running your server again, make sure MongoDB server is running. Open another terminal, then type this command to start MongoDB server.
mongod
Now, open and edit app.js in the root of project folder using your favorite text editor or IDE. Declare mongoose in require sections.
var mongoose = require('mongoose');
Use mongoose with native Node Promise.
mongoose.Promise = global.Promise;
Create a connection to MongoDB.
mongoose.connect('mongodb://localhost/product')
  .then(() =>  console.log('connection succesful'))
  .catch((err) => console.error(err));
Next, run the node app again.
npm start
You should see this message on the terminal. It's mean connection to MongoDB is successful.
> [email protected] start /Users/didin/Documents/NodeApps/node-rest-api
> node ./bin/www

connection successful

 

3. Create Product Mongoose Model

Now, create models directory and javascript file as the model. Before doing that, stop node server by pushing CTRL+C key in the terminal.

mkdir models
touch models/Product.js
Open and edit Product.js file the add this lines of codes.
var mongoose = require('mongoose');

var ProductSchema = new mongoose.Schema({
  prod_name: String,
  prod_desc: String,
  prod_price: Number,
  updated_at: { type: Date, default: Date.now },
});

module.exports = mongoose.model('Product', ProductSchema);
That Schema will mapping to MongoDB collections called product. If you want to know more about Mongoose Schema Datatypes you can find it here.


4. Create Routes for REST API endpoint

Our REST API that we build will have following functions.

Method Endpoints Notes
GET  /product Get all products
GET  /product/:id Get single product
POST  /product Add product
PUT  /product/:id Update product
DELETE  /product/:id Delete product

To achieve that, add the javascript file to routes folder.

touch routes/products.js

Open and edit routes/products.js then add this lines of codes.

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Product = require('../models/Product.js');

/* GET ALL PRODUCTS */
router.get('/', function(req, res, next) {
  Product.find(function (err, products) {
    if (err) return next(err);
    res.json(products);
  });
});

/* GET SINGLE PRODUCT BY ID */
router.get('/:id', function(req, res, next) {
  Product.findById(req.params.id, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

/* SAVE PRODUCT */
router.post('/', function(req, res, next) {
  Product.create(req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

/* UPDATE PRODUCT */
router.put('/:id', function(req, res, next) {
  Product.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

/* DELETE PRODUCT */
router.delete('/:id', function(req, res, next) {
  Product.findByIdAndRemove(req.params.id, req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

module.exports = router;

Next, open and edit app.js then add product route as require after users require.

var products = require('./routes/products');

Then add use after use of users.

app.use('/products', products);

 


5. Test REST API Endpoints

After everything is ready, this time to testing our created Node.js, Express.js, Mongoose.js and MongoDB REST API. There are so many tools for testing REST API, but for now, we are testing using CURL from the terminal.

We start with Add/Save product data first. Open new terminal tab or windows the type this command.

curl -i -X POST -H "Content-Type: application/json" -d '{ "prod_name":"XBox One","prod_desc":"New Microsoft XBox One, the latest games console","prod_price": 520 }' localhost:3000/products

If you get the response like below, then you save new product successfully.

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 185
ETag: W/"b9-ymiFjoNdt5wABoii1CiYbg"
Date: Sun, 19 Feb 2017 03:30:35 GMT
Connection: keep-alive

{"__v":0,"prod_name":"XBox One","prod_desc":"New Microsoft XBox One, the latest games console","prod_price":520,"_id":"58a9115abed027087df7133b","updated_at":"2017-02-19T03:30:34.415Z"}

We can create the same POST with different data to populate more record to product collection.

curl -i -X POST -H "Content-Type: application/json" -d '{ "prod_name":"Sony PS 4","prod_desc":"Sony playstation 4","prod_price": 580 }' localhost:3000/products

Next, we are testing to get all products data using this command.

curl -i -H "Accept: application/json" localhost:3000/products

That command will response products data with JSON format.

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 344
ETag: W/"158-V1WRYZrNC8yW7HFEfOSSew"
Date: Sun, 19 Feb 2017 03:34:26 GMT
Connection: keep-alive

[{"_id":"58a9115abed027087df7133b","prod_name":"XBox One","prod_desc":"New Microsoft XBox One, the latest games console","prod_price":520,"__v":0,"updated_at":"2017-02-19T03:30:34.415Z"},{"_id":"58a91204bed027087df7133c","prod_name":"Sony PS 4","prod_desc":"Sony playstation 4","prod_price":580,"__v":0,"updated_at":"2017-02-19T03:33:24.941Z"}]

Next, we are testing to get one product by id using this command.

curl -i -H "Accept: application/json" localhost:3000/products/58a91204bed027087df7133c

The response should be like this.

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 156
ETag: W/"9c-NYW3p4BkPVbiNf05Ezj+zA"
Date: Sun, 19 Feb 2017 03:45:48 GMT
Connection: keep-alive

{"_id":"58a91204bed027087df7133c","prod_name":"Sony PS 4","prod_desc":"Sony playstation 4","prod_price":580,"__v":0,"updated_at":"2017-02-19T03:33:24.941Z"}

Next, we are editing and update one of a product by id using this command. First, copy id from one of product from the response before then paste it as the parameter.

curl -i -X PUT -H "Content-Type: application/json" -d '{"prod_desc":"Microsoft XBox One"}' localhost:3000/products/58a9115abed027087df7133b

It should response like this.

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 185
ETag: W/"b9-k9Wipgusc9JVZAMyHgjVXw"
Date: Sun, 19 Feb 2017 03:38:24 GMT
Connection: keep-alive

{"_id":"58a9115abed027087df7133b","prod_name":"XBox One","prod_desc":..

Finally, we are testing for delete one product by id using this command.

curl -i -X DELETE localhost:3000/products/58a9115abed027087df7133b

It will response like this and product with that id will be removed from product collection.

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 155
ETag: W/"9b-pP1KXaQhyqcMkvBlLa6pFQ"
Date: Sun, 19 Feb 2017 03:41:54 GMT
Connection: keep-alive

{"_id":"58a9115abed027087df7133b","prod_name":"XBox One","prod_desc":"Microsoft XBox One","prod_price":520,"__v":0,"updated_at":"2017-02-19T03:30:34.415Z"}

 

6. Quick REST API Creation using Node-Restful Library

There are so many method and library for creating REST API quicker and elegant. One of them that I found is the Node-Restful library that you can find on Github. Just add the library using npm command.

npm install node-restful --save

Open and edit app.js on the root of the project. Add require line for Node-Restful and Method-Override.

var restful = require('node-restful');
var methodOverride = require('method-override');

Change "bodyParse extended" value to true then add this lines.

app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json({type:'application/vnd.api+json'}));
app.use(methodOverride());

Create mongoose model that use together with Node-Restful library. Right now we are creating "category" model.

var Category = app.resource = restful.model('category', mongoose.Schema({
  cat_name: String,
}))
.methods(['get', 'post', 'put', 'delete']);

Category.register(app, '/category');

Run again the app and test it using previous way for testing REST API. You can compare with another framework that I write on this website. By the way, this the full source code on Github.

Thanks.

The following resources might be useful for you:

Loading…