Full HTTPS REST server in Node.js

Categories Mozilla, nodejs, Open Technologies, Technologies

I will show you now, how to write a simple HTTPS JSON REST server using node.js components. Grab a beer, open your IDE and let’s start hacking.

0. Create certificates.

If you don’t have valid https certificates, you can generate one for testing purposes. If you need one cool certificate, you can join cacert community. Anyway, let’s openssl for a while:

openssl genrsa -out privatekey.pem 1024 
openssl req -new -key privatekey.pem -out certrequest.csr 
openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

1. Install additional modules.

We will need just one aditional module, called journey.

It’s working only in JSON mode, but anyway I don’t like XML REST at all. JSON is the future, baby.

npm install journey

2. Writing the router.js file.

– Define the modules required:

var journey = require('journey');
var https = require('https');
var fs = require('fs');

– Define the certificates part:

var privateKey = fs.readFileSync('../certs/privatekey.pem');
var certificate = fs.readFileSync('../certs/certificate.pem');

var options = {
  key: privateKey,
  cert: certificate
};

– Define the router that will handle all REST requests (GET, POST, PUT, DELETE):

var mrouter = new (journey.Router)();

– Define the map of all requests. In other words what to do when the router receive a request:

mrouter.map(function () {
// Default URL
this.root.bind(function (req, res) { res.send("Welcome to my application") });

//GET request on /databases
this.get('/databases').bind(function (req, res) {
do something
});

//GET request on a specific database - /database/users21
this.get(/^databases\/([A-Za-z0-9_]+)$/).bind(function (req, res, id) {
	 //id contains 'users21' part       
 });

/**PUT request example. 
* You can deal with as many parameters as you need, just write the regexp for it and assign a parameter. 
* Here is an example to update a document on a collection on MongoDB database. 
* We have 3 user parameters - 6 parameters in URL:
**/
this.put(/^databases\/([A-Za-z0-9_]+)\/collections+\/([A-Za-z0-9_]+)\/documents+\/([A-Za-z0-9_]+)$/).bind(function (req, res, dbid, collid, docid, data) {
	        res.send('update '+docid+ 'in '+collid + 'on: '+ dbid);
 });
}); //end mapping

3. And the last thing we should do is to turn on the HTTPS server and the router

https.createServer(options,function (request, response) {
    var body = "";

    request.addListener('data', function (chunk) { body += chunk });
    request.addListener('end', function () {

        mrouter.handle(request, body, function (result) {

            response.writeHead(result.status, result.headers);
            response.end(result.body);
        });
    });
}).listen(8081);

4. Run and connect your JSON client on httpS://127.0.0.1:8081 to test it.

node router.js

One file to rule them all

Here you can see the whole WORKING simple app including nice tricks like adding settings and whole bunch of regexp examples for handling the URL parameters.

Enjoy!

7 Comments

  • Mardeg
    July 20, 2011

    Can this become a restartless add-on for Firefox? I miss Plain Old Webserver :(

  • MongoDB, Node.js and admin auth | TalkWeb
    July 20, 2011

    […] posts:Full HTTPS REST server in Node.jsI will show you now, how to write a […]

  • karl
    July 21, 2011

    It is a very cool HTTP server tutorial, but has barely anything to do with REST. Remove the REST prose and the tutorial still stands for its own value.

    As for being REST, a RESTful interface is driven by an hypermedia interface.

    • Bogo
      July 21, 2011

      It’s a nice way to implement RESTful JSON API communication. It follows all REST logic

  • karl
    July 21, 2011

    :)

    It would partially if you had a notion of links in JSON. JSON doesn’t have unfortunately. There is work in that direction done. See for example the work done by Zyp.
    http://tools.ietf.org/html/draft-zyp-json-schema-03#section-6.1

    One way to make JSON more compatible with a RESTful API would be using HTTP Link with rel values

    For example:

    Link: ; rel=”next”

    As for the rationale about hypertext driven for RESTful APIs, I recommend reading.
    http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

    As I said the article is cool for explaining what is a real HTTP server :) but nothing much to do with RESTful. :)

  • Philipp Dunkel
    July 23, 2011

    For anyone interested, I created a little script that creates a CA on a *NIX machine.

    simply run:

    #> ./create-sh.sh
    #> echo “01” > serial

    then you have your CA where you can simply create certificates using GNU-Make

    like:

    #> make philipp.p12

    or

    #> make philipp.crt

    Download from: http://www.box.net/shared/8ue3k7f5pjfau614zznc and have fun with it

    • Bogo
      July 26, 2011

      Thanks Philipp

Leave a Reply to Philipp Dunkel Cancel reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.