At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

, ,

Restful API using MEAN stack

  • By Arunkumar Nattarayan
  • November 17, 2016
  • 1061 Views

This article explores the basics of the MEAN stack, shows how to create a DB Connection and also Create APIs (GET, POST, DELETE).

Prerequisites to be in your machine:

* Node
* MongoDB

Installations to be done:

* npm install express –save
Before going into the application setup, we need to know what is MEAN stack.

What is MEAN stack?

The term MEAN stack refers to a collection of JavaScript based technologies used to develop web applications. MEAN is an acronym for MongoDB, ExpressJS, AngularJS and Node.js. From client to server to database, MEAN is full stack JavaScript. This article describes the basics of the MEAN stack and shows how to create a simple bucket list application.
Other basic definitions that are to be known:
* Node.js is a server side JavaScript execution environment. It’s a platform built on Google Chrome’s V8 JavaScript runtime. It helps in building highly scalable and concurrent applications rapidly.
* Express is lightweight framework used to build web applications in Node. It provides a number of robust features for building single and multi page web application. Express is inspired by the popular Ruby framework, Sinatra.
* MongoDB is a schemaless NoSQL database system. MongoDB saves data in binary JSON format which makes it easier to pass data between client and server.
* AngularJS is a JavaScript framework developed by Google. It provides some awesome features like the two-way data binding. It’s a complete solution for rapid and awesome front end development.

Create the Application Structure:

We are going to create an application called MyBooks where you can create, edit and delete your own books. Let’s create the application structure using the application generator tool, “express-generator”, to quickly create an application skeleton.
For this purpose, give the following command:
* $express mybooks

DB Connection:

Create a folder called db and create the file called connector.js which will provide the DB connections.
mybooks/db/connector.js is the file that is going to serve the mongodb connection for our mybooks application by the help of MongoClient object. To create an object so as to interact with the MongoDB:

var MongoClient = require('mongodb').MongoClient

 
The state variable holds the db connection.

var state = {
db: null,
}

 
Connect the db through the MongoDB connection string in url format

exports.connect = function(url, done) {
if (state.db) return done()
MongoClient.connect(url, function(err, db) {
if (err) return done(err)
state.db = db
done()
})
}

 
Return the connection object which is used in the DB operations

exports.get = function() {
return state.db
}

 
Finally, we close the DB connection:

exports.close = function(done) {
if (state.db) {
state.db.close(function(err, result) {
state.db = null
state.mode = null
done(err)
})
}
}

 
In our example, by default, the server setup exists in the mybooks/bin/www. Here, we will establish the db connection.
We are going to create the db connection at the beginning of the application itself, and it will hold good till the end of it, without having to establish connections for each db operation. To do this:
Find the Following lines in www
server.listen(port);
server.on(‘error’, onError);
server.on(‘listening’, onListening);
replace this lines with the following lines

db.connect("PROVIDE YOUR MONGODB CONNECTION STRING IN URL FORMAT", function(err) {
if (err) {
console.log('Unable to connect to Mongo.')
process.exit(1)
} else {
server.listen(port);
console.log('Listening on port '+port+"....")
server.on('error', onError);
server.on('listening', onListening);
}
})

 
If at all there is some error in the db connection, the application itself will not get started.
lets create a file called api.js inside the router folder. In our case, it shall be mybooks/routes/api.js.

Performing Operations on the DB with the connection that we have created:

1. To create the records in collection:

var db = require('../db/connector.js');
var collection = db.get().collection('books'),
app.post("/books", function(req, res) {
var newBook = req.body;
collection.insertOne(newBook, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new Book.");
} else {
res.status(201).json(doc.ops[0]);
}
});
});

 
2. To find the record with the collection id

app.get("/books/:id", function(req, res) {
collection.findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get Book");
} else {
res.status(200).json(doc);
}
});
});

 
3. Update the document in collection by id

app.put("/books/:id", function(req, res) {
var updateDoc = req.body;
delete updateDoc._id;
collection.updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to update Book");
} else {
res.status(204).end();
}
});
});

 
4. And finally, Delete the document by id:

app.delete("/books/:id", function(req, res) {
collection.deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
if (err) {
handleError(res, err.message, "Failed to delete Book");
} else {
res.status(204).end();
}
});

 
Last but not least, we shall include the common error handling function that shall deal with all connection errors.

function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}

 

Conclusion:

Now, we have to run the application in order for the setup to take effect. For this, we provide the command:
npm start
This will run the application, the default being http://localhost:3000.
Using a third party API test tool like postman, we can access our APIs through the appropriate URLs.
In this article we have learnt the basics of Mean stack and how to connect the db and perform CRUD operations through the API.