Saturday, January 19, 2013

Versioned APIs with Express

After reading and watching some of the stuff coming out from Apigee about API Design, I've been convinced that APIs should probably be versioned in the URL using a scheme like this:
http://api.whatever.com/v1/jobs

By the time I realized this the API I had been building with node.js was basically already complete, so I was a little bit sad that I'd have to come up with some complicated versioning scheme.

After a bit of fretting I realized that express can handle this super easy using an interesting feature of the express() instance that it can be mounted to another route using app.use().

This means that your routes don't know which version they are!

Here's your main app file.

app.js file

Then you'll put each version of your API in the routes/ folder named after the version.

routes/v0.js file
Each version of the API can have middleware (such as unique authentication) that only works on that version of the API. One thing that this doesn't cover is unique models per version, but I'll leave that up to you to figure out how to accomplish, because the needs of each app very quite a bit by app. Hope this tip helps!

No comments:

Post a Comment