Editor’s note: We found an interesting series of articlesLearn 30 New Technologies in 30 Days, is being translated, an update a day, year-end gift package. Here’s day 27.


Today I decided to learn a Node.js module called restify. The Restify module makes it much easier to write the correct REST API in Node.js, and it also provides out-of-the-box support such as version control, error handling, CORS, and content negotiation. It borrows heavily from Express (intentionally), as this is more or less the de facto API for writing web applications on Node.js and storing data in MongoDB.

Restify preparation

Restify requires the NodeJS and NPM package manager, which can be the default when Node.js is installed. If you already have Node.js and NPM installed, you can use the NPM system to install HARP.

This application uses MongoDB as the data store.

Restify installation

Create a new directory on the file system in any convenient directory:

$ mkdir myapp
$ cd myapp

Enter the following command to install the Restify module:

$ npm install restify

To install the MongoJS module using MongoJS as the driver for MongoDB, enter the following command:

$ npm install mongojs

Write a REST-based API

Now that you have installed Restify and MongoJS create a new file called app.js:

$ touch app.js

Paste the following into app.js:

var restify = require('restify');
var mongojs = require("mongojs");

This is to load the Restify and MongoJS modules and assign variables to them.

Now, create a new server that uses the Restify API:

var restify = require('restify'); var mongojs = require("mongojs"); Var ip_addr = '127.0.0.1; var port = '8080'; var server = restify.createServer({ name : "myapp" }); server.listen(port ,ip_addr, function(){ console.log('%s listening at %s ', server.name , server.url); });

The createServer() function takes a selection object and passes it myApp as the name of the server for the selection object. You can also see the full list of options in this document. After the server instance is created, the Listen function is called with the port, IP address, and a callback function.

Run the program:

$ node app.js

You will then see the following command line:

Myapp listening at http://127.0.0.1:8080

Configure the plug-in

The Restify module has a number of built-in plugins. Copy and paste the following into app.js and should be added before the server.listen() function. See this documentation for all supported plug-ins.

server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(restify.CORS());

The above code represents:

  1. restify.queryParser()Plug-ins are used to parse HTTP query strings (e.g/jobs? skills=java,mysql), the parsed content will be inreq.queryIn available.
  2. Restify.bodyParser () automatically converts the request data to JavaScript objects on the server.
  3. Restify.cors () configures CORS support in the application.

Mongo configuration

Before adding the route, add the code to connect to the MongoDB database of MyApp:

Var connection_string = '127.0.0.1:27017 / myapp'; var db = mongojs(connection_string, ['myapp']); var jobs = db.collection("jobs");

You are now connected to your local MongoDB instance. Next, you need to get a working set that uses the database objects.

Write the CRUD API

At this point, the server and database are ready. Still need to find a way to define the behavior of the API, copy and paste the following code into the app.js file:

Var PATH = '/jobs' server.get({PATH: PATH, version: '0.0.1'}, findAllJobs); Server. get({path: path +'/: jobID ', version: '0.0.1'}, findJob); Server.post ({path: path, version: '0.0.1'},postNewJob); Server. del({path: path +'/: jobID ', version: '0.0.1'},deleteJob);

The above code does the following:

  1. When the user issues a GET request to ‘/jobs’,findAllJobsThe callback function will be called.
  2. When the user issues a GET request to ‘/ jobs/123’,findJobThe callback function will be called.
  3. When a user makes a POST request ‘/jobs’,postNewJobThe callback function will be called.
  4. When the user deletes the request ‘/ jobs/123’,deleteJobThe callback will be invoked.

Now write the callback function, copy and paste it into app.js:

function findAllJobs(req, res , next){ res.setHeader('Access-Control-Allow-Origin','*'); jobs.find().limit(20).sort({postedOn : -1} , function(err , success){ console.log('Response success '+success); console.log('Response error '+err); if(success){ res.send(200 , success); return next(); }else{ return next(err); }}); } function findJob(req, res , next){ res.setHeader('Access-Control-Allow-Origin','*'); jobs.findOne({_id:mongojs.ObjectId(req.params.jobId)} , function(err , success){ console.log('Response success '+success); console.log('Response error '+err); if(success){ res.send(200 , success); return next(); } return next(err); }) } function postNewJob(req , res , next){ var job = {}; job.title = req.params.title; job.description = req.params.description; job.location = req.params.location; job.postedOn = new Date(); res.setHeader('Access-Control-Allow-Origin','*'); jobs.save(job , function(err , success){ console.log('Response success '+success); console.log('Response error '+err); if(success){ res.send(201 , job); return next(); }else{ return next(err); }}); } function deleteJob(req , res , next){ res.setHeader('Access-Control-Allow-Origin','*'); jobs.remove({_id:mongojs.ObjectId(req.params.jobId)} , function(err , success){ console.log('Response success '+success); console.log('Response error '+err); if(success){ res.send(204); return next(); } else{ return next(err); }})}

Using curl to test the Web service, type the following command to create a “job” :

$ curl -i -X POST -H "Content-Type: application/json" -d '{"title":"NodeJS Developer Required" , "description":"NodeJS Developer Required" , "Location" : "Sector 30, Gurgaon, India"} 'http://127.0.0.1:8080/jobs

Find all the “jobs” :

$curl - is http://127.0.0.1:8080/jobs HTTP / 1.1 200 OK Access - Control - Allow - Origin: * the content-type: application/json Content-Length: 187 Date: Sun, 24 Nov 2013 16:17:27 GMT Connection: keep-alive [{"title":"NodeJS Developer Required","description":"NodeJS Developer Required","location":"Sector 30, Gurgaon, India, "" postedOn" : "the 2013-11-24 T16: company. 688 z", "_id" : "52922650 aab6107320000001}]" "

Deploy to the cloud

Before the application is deployed to OpenShift, set the following Settings:

  1. Sign up for an OpenShift account, which is completely free and can be allocated 1.5 GB of memory and 3 GB of disk space per user.
  2. To install the RHC client tools, you need Ruby 1.8.7 or later. If you already have Ruby Gem, entersudo gem install rhc, make sure it’s the latest version. To update RHC, execute the commandsudo gem update rhc. For additional assistance in installing RHC command-line tools, please refer to this page:https://www.openshift.com/developers/rhc-client-tools-install
  3. throughrhc setupCommand to set up your OpenShift account. This command will help you create a namespace and upload your SSH keys to the OpenShift server.

After the setup is complete, enter the following command to create a new OpenShift application:

$RHC create-app day27demo nodejs-0.10 mongodb-2 --from-code https://github.com/shekhargulati/day27-restify-openshift-demo.git

It does everything from creating an application, setting up a public DNS, creating a private Git repository, and finally deploying the application from the GitHub repository using code. The application can be accessed here at http:// day27demo-{domain-name}.rhcloud.com//

That’s all for today. Feedback is welcome.


Day 27: Restify–Build Correct REST Web Services in Node.js