Create Database
Create a database with the name is learnexpressjsrestapi. This database have 1 collection: Product collection
/* Create learnexpressjsrestapi database */
use learnexpressjsrestapi
/* Create Product collection */
db.createCollection('product');
/* Dumping data for `product` collection */
/* 1 */
{
"_id" : ObjectId("5a77af0153b19a9778e45023"),
"name" : "Mobile 1",
"price" : 45.0,
"quantity" : 4.0,
"status" : true
}
/* 2 */
{
"_id" : ObjectId("5a77af0153b19a9778e45024"),
"name" : "Mobile 2",
"price" : 12.0,
"quantity" : 7.0,
"status" : true
}
/* 3 */
{
"_id" : ObjectId("5a77af0153b19a9778e45025"),
"name" : "Mobile 3",
"price" : 28.0,
"quantity" : 8.0,
"status" : true
}
/* 4 */
{
"_id" : ObjectId("5a77af0153b19a9778e45026"),
"name" : "Laptop 1",
"price" : 39.0,
"quantity" : 12.0,
"status" : false
}
/* 5 */
{
"_id" : ObjectId("5a77af0153b19a9778e45027"),
"name" : "Laptop 2",
"price" : 86.0,
"quantity" : 23.0,
"status" : true
}
/* 6 */
{
"_id" : ObjectId("5a77af0153b19a9778e45028"),
"name" : "Tivi 1",
"price" : 22.0,
"quantity" : 7.0,
"status" : true
}
/* 7 */
{
"_id" : ObjectId("5a77af0153b19a9778e45029"),
"name" : "Tivi 2",
"price" : 86.0,
"quantity" : 23.0,
"status" : false
}
Create Server Project
Create LearnExpressJSRestAPIWithRealApps folder and select to this folder in Visual Studio Code
Install Mongoose
Use the following command to install Mongoose:
npm install mongoose --save
Install Express.JS
Use the following command to install Express.JS:
npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save
Define Schema
Create schemas folder in Node project. Create product.schema.js file into schemas folder. Declare schema for product collection as below:
var mongoose = require('mongoose');
var ProductSchema = new mongoose.Schema(
{
name: String,
price: Number,
quantity: Number,
status: Boolean
},
{
versionKey: false
}
);
module.exports = mongoose.model('Product', ProductSchema, 'product');
Create Rest API
Create a new folder named api inside the server project. Create product.api.js file inside api folder contains Rest APIs provides application/json data for the client
var mongoose = require('mongoose');
var Product = require('../schemas/product.schema');
var ProductAPI = {
find: function (request, response) {
Product.findById(request.params.id, function (error, product) {
if (error) {
throw error;
} else {
response.status(200).json(product);
}
});
}
};
module.exports = ProductAPI;
Create Rest API Routing
Inside the api folder create a new file named index.js. This file will hold all the routes needed for rest api in server.
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
mongoose.connect('mongodb://localhost:27017/learnexpressjsrestapi');
var ProductAPI = require('./product.api');
router.get('/product/find/:id', ProductAPI.find);
module.exports = router;
Create Rest API Server
At the root of server project, create a file named server.js. This will be the entry point into node application. This will start the server and listen on a local port
var express = require('express');
var app = express();
app.use('/api', require('./api/index'));
var server = app.listen(9090, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Server listening at http://%s:%s", host, port)
});
Structure of Server Project
Test Rest API Server
At the root of server project run command: node server.js
Access Rest API use the following url: http://localhost:9090/api/product/find/5a77af0153b19a9778e45024
Output
{"_id":"5a77af0153b19a9778e45024","name":"Mobile 2","price":12,"quantity":7,"status":true}
Create Client Project
Create LearnExpressJSRestAPIWithRealApps_Client folder and select to this folder in Visual Studio Code
Install Modules
Use the following command to install http module
npm install http --save
Create Rest API Client
Create a new folder named api inside the client folder. Create product.api.js file inside api folder contains method call Rest API from server
var http = require('http');
var BASE_URL = 'http://localhost:9090/api/';
var ProductAPIClient = {
find: function (id, callback) {
return http.get(BASE_URL + 'product/find/' + id, function (response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
callback({
status: response.statusCode,
body: JSON.parse(str)
});
});
response.on('error', function (error) {
callback({
status: response.statusCode,
error: error.message
});
});
}).end();
}
};
module.exports = ProductAPIClient;
Structure of Client Project
Test Client Project
At the root of client project, create a file named client.js. This will call Rest API and display results
var ProductAPIClient = require('./api/product.api');
ProductAPIClient.find('5a77af0153b19a9778e45024', function (result) {
if (result.error) {
console.log(result.error)
} else {
console.log('Status: ' + result.status);
console.log('Product Info');
console.log('Id: ' + result.body._id);
console.log('Name: ' + result.body.name);
console.log('Price: ' + result.body.price);
console.log('Quantity: ' + result.body.quantity);
console.log('Status: ' + result.body.status);
}
});
Output
Status: 200
Product Info
Id: 5a77af0153b19a9778e45024
Name: Mobile 2
Price: 12
Quantity: 7Status: true