What does a Node.js web service look like?

javascript, node.js, web-services

Solution

If Express would be your web framework, look at the express-resource (Github) middleware for routing an API. You define resources and it'll wire up REST-style routing for you with very little boilerplate.

app.resource('horses', require('./routes/horses'), { format: json })

Given the above, express-resource will hook up all the REST-style routes to actions you supply, returning JSON by default. In `routes/horses.js`, you export actions for that resource, along the lines of:

exports.index = function index (req, res) {
  // GET http://yourdomain.com/horses
  res.send( MyHorseModel.getAll() )
}

exports.show = function show (req, res) {
  // GET http://yourdomain.com/horses/seabiscuit
  res.send( MyHorseModel.get(req.params.horse) )
}

exports.create = function create (req, res) {
  // PUT http://yourdomain.com/horses
  if (app.user.canWrite) {
    MyHorseModel.put(req.body, function (ok) { res.send(ok) })
  }
}

// ... etc

You can respond with different representations:

exports.show = {
  json: function (req, res) { 
    // GET http://yourdomain/horses/seabiscuit.json
  }
, xml: function (req, res) {
    // GET http://yourdomain/horses/seabiscuit.xml
  }
}

Middlewares like express-resource can make life with Node and Express much easier, take a look through the examples on github to see if it'll do what you need.

Problem

I am taking a look at Node.js and thinking about using it for building an API. From what I can tell, ExpressJS would be the web framework and is not what I'd be looking for to solve this. So what would a web service look like? Would it simply be creating a server, talking to mongo and returning results? Also, what does routing look like? (I'd obviously want to 'design' the routes).

Original source