Build a REST api under five minutes

The paradigm of computing is changing dynamically. Now, it is the era of mobile computing. What’s that? Pretty simple. All you need is a smartphone be it an Android or an iPhone or a Lumia; and the entire world is yours. The app stores and markets are flooding with millions of apps uploaded/updated everyday. Clearly, mobile apps are the developer’s paradise today.

That brings us to the next part of our discussion. The mobile can do everything that our computer does. Take an example. An app called Foursquare. It is existing as a web service as well as an app. Both can pretty much do the same. The website runs on a browser in a PC/Mac with configurations such as i5 processor and 4GB RAM, while the same app version runs on a mobile device with configuration such as Qualcomm processor and 512 MB RAM. Here’s how they look on different versions.

F
Foursquare PC vs Mobile version.

The trick here is that the client apps do not do the maximum processing. They simply interact with the server which performs most of the processing and returns the response to the mobile apps. That brings us to the obvious question – How do they interact? Answer: via the API.

Here, we are only interested in RESTful APIs. REST api is a very simple form of API(Application Programming Interface) which interacts with the server via some explicit URL patterns that are used either to fetch data from server(GET) or to send data to server(POST). More study on REST can be done here. Now, this REST request looks like this and you might be quite familiar to that:

 GET api.example.com/user/xyz 

The purpose of using REST is that when the mobile app sends a request to your server to GET the contents of a particular user, it returns the data in a portable format be it XML or JSON. It typically looks like this:

{
   "_id": "xyz",
   "code": "N/A",
   "email": "xyz@hotmail.com",
   "joinDate": "2015-09-20T05:59:30.675Z",
   "lat": "22.64999833333333",
   "lon": "88.45",
   "name": "XYZ",
   "token": "86f7a143bc4f1f4c"
}

Now its the job of the mobile app code to parse the JSON response and format it accordingly. Thus, the entire architecture looks like:

2
Architecture of Workflow

Now how can you build such an API under 5 minutes? Easy. You need three things:

  1. NodeJS
  2. Restify framework
  3. MongoDB
A server using Restify and Nodejs looks very simple like this:
var mongojs = require('mongojs');
var restify = require('restify');
var request = require('request');
var ip_addr = '127.0.0.1';
var port = process.env.PORT || 1337;
var fs = require('fs');

/*****************************Modules req**************************/
var config = require('./modules/config.js');


var server = restify.createServer({
 name : "API started..."
});

server.listen(port , function(){
 console.log('started %s', server.name);
});

Create a folder called modules in root folder and create a file called config.js in it wher we will store all connection strings like those for MongoDB connection.

module.exports = {
 mongoString : "mongodb://example.com/exampledb"
}

You can get a free 500MB of mongodb from MongoLab. Replace the mongoString with your connection string. The DB is now setup. All we need to do is POST and GET. We don’t need to write explicit Models, Views and Controller as restify takes care of all those in NodeJS.
Creating routes for user:

/*************************MongoDB Server****************************/
var connection_string = config.mongoString;
var db = mongojs(connection_string, ['dbname'], {authMechanism: 'ScramSHA1'});
var user = db.collection("user");
/******************************Routes******************************/

//==================================================================//
//USER Routes
var USER_PATH = '/user'
server.get({path : USER_PATH , version : '0.0.1'} , findAllUsers);
server.post({path : USER_PATH , version: '0.0.1'} ,createUser);
//==================================================================//

/*****************************Functions****************************/

//==================================================================//

function createUser(req , res , next){
 var _user = {};
 
 _user._id = req.params.id;
 _user.name = req.params.name;
 _user.email = req.params.email;
 _user.joinDate = new Date();

 res.setHeader('Access-Control-Allow-Origin','*');

 user.save(_user , function(err , success){
 console.log('Response success '+success);
 console.log('Response error '+err);
 if(success){
 res.send(201 , _user);
 return next();
 }else{
 return next(err);
 }
 });
}


function findAllUsers(req, res , next){ //finds all users listed
 res.setHeader('Access-Control-Allow-Origin','*'); //header set for CORS request
 user.find().limit(20).sort({postedOn : -1} , function(err , success){ //limit of 20 users
 //console.log(_token);
 console.log('Response error '+err);
 if(success){
 res.end(JSON.stringify(success,null,3)); //JSON response
 }else{
 return next(err);
 }

 });
}

The coding part is done. Now run the server as node app.js. Your server will be running at:
http://localhost:1337
Download Postman from Google Chrome Store.
Open Postman and enter the http://localhost:1337 as url and enter parameters as:

http://localhost:1337/user?id=983266789&name=abhishekdey&email=gs@hotmail.com

Choose method type as POST and hit Send.
Screen Shot 2015-11-12 at 1.12.32 PM

And there you go. This is how you create a Data entry. Now simply redirect your browser to
http://localhost:1337/user and you can have the JSON response of user.

This is just a tutorial and hope it helps you guys. Building an API is not rocket science anymore. Its easy and you can do it under 5 minutes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s