Creating a RESTful webservice with Node.JS

We wanted to create a scalable REST webservice that could be used to access some backend data in our application. I had heard about Node.js but hadn’t actually used it for anything.  This seemed like the ideal situation to give it a try.  Node.js seems to have been built on the concept of having it run on semi-reliable servers and to operate in a “multi-node” style architecture, which is exactly what we want to do. In this post I’ll show you how to build a RESTful webservice using Node.js.

So… I bought and read the “The Node Beginner Book” (ebook) by Manuel Kiessling which was a very good introduction to node.js.  It also provided a bit of javascript intro and is very relevant to building a RESTful web service as it talks about concepts that can be directly applied.  I’d recommend it for people new to Node.js (but who already have a development background).

Now that I had some background on Node.js, I did some reading on REST and Node.js and found that there is a great library called Restify.  This library is designed to do exactly what we want by taking all the overhead of coding the REST and webserver and allows you to just create functions to respond to whatever requests you choose.  Nice, that makes life easy.

So, we use the node package manager (npm) to download and install it.

npm install restify

Now that we’ve installed the restify module, we can create a web-service in Node.js very easily.  Below is a simple script showing (in a very basic way) how you might use Restify.  This script is acting as a simple web-service which allows the client to lookup user records or individual attributes of user records.  Because it’s just an example, I’ve left out the part where you might retrieve the user records and instead I just have a single hard-coded record that we return.  Lets get to the script…

var SERVER_PORT = 8800;

var restify = require('restify');
var server = restify.createServer();

var example_record = {user_id : '2', username : 'jsmith', 
    first_name : 'John', last_name : 'Smith'};

var respond_attribute = function(req, res, next) {
	requested_attribute = req.params.attrib_name;
	requested_id = req.params.id;

	// Check if they are requesting our example record
	if(example_record.user_id == requested_id) {
		// Make sure it's a valid attribute
		if(example_record.hasOwnProperty(requested_attribute)) {
			// Send back only the attribute requested
			var return_data = {};
			return_data[requested_attribute] = example_record[requested_attribute];
			res.send(return_data);
			next();
		} else {
			// Return an error
			next( new Error("Invalid user attribute") );
		}
	} else {
		// Return an error
		next(new Error("Invalid user ID specified"));
	}
}

var respond_record = function(req,res,next) {
	requested_attribute = req.params.attrib_name;
	requested_id = req.params.id;

	// Check if they are requesting our example record
	if(example_record.user_id == requested_id) {
		// Send back the full record
		res.send(example_record);
	} else {
		// Return an error
		next(new Error("Invalid user ID specified"));
	}
}

var server_up = function() {
	console.log("Example REST webservice running on " + server.url);
}

// We setup the routes to specify how requests to the server will be handled
// In this case we are going to listen for user ID requests and user ID + attribute requests
server.get("/users/:id",respond_record);
server.get("/users/:id/:attrib_name",respond_attribute);

server.listen(SERVER_PORT, server_up);

This script starts by creating an instance of the Restify object.  It then defines two functions, one to respond to requests for user attributes and one to return full user records.  These two functions are the logic of the web-service.  We then get to these two lines:

server.get('users/:id',respond_record);
server.get('users/:id/:attrib_name',respond_attribute);

This is really where Restify makes your life easier.  In the first line, we are saying.  When you get an HTTP GET request, which is directed at the “users” API, treat the next part of the URL as the parameter named “id” and use the “respond_record” function to respond to it.  The second line defines another type of request for a URL which specifies both an ID and an attribute name.  These are acting as our methods of routing requests that are received by the web-service to various handler functions.  Those handler functions then specify what will be returned to the client.

If you save the above code in a file called “restful.js”, you can then run the following command to start the web-service and you should see the output below:

node restful.js
Example REST webservice running on http://0.0.0.0:8800

Cool, we have a functional RESTful webservice with a VERY small amount of code/work.

You can go ahead and test this by opening up a web-browser and visiting http://localhost:8800/users/2/username which will return a JSON object which tells you the username of the user with ID 2.  You can also visit http://localhost:8800/users/2 which will return the full user record.

Now depending on your need, you might also want to accept POST requests to create records or perform other functions and you would do this by simply creating handlers the same way we did for GET requests but by using:

server.post('/users/create',respond_create);

Now your respond_create function will receive the posted data and you can return results.  Read through the restify documentation for more info on that.

Hopefully that gives people a good starting point for creating a RESTful webservice using Node.js and Restify.

1 thought on “Creating a RESTful webservice with Node.JS”

Leave a Comment