In Internet & Development

Sooner or later most developers hit the point where they want or need to update their API without having all of the people who already use it have to update their code. This is where versioning your api comes into play.

It allows you to update your API and even introduce breaking changes without having all your users update their code. There are some ways to accomplish that…

Version your API: 3 wrong ways

Troy Hunt published a great article where he describes 3 wrong ways to version your api. It is really worth reading it. The bottomline of it is that there is no 100% right way to do it.

The 3 ways he talks about are:

  • URL versioning (e.g. /v1/foo/bar)
  • custom request header (e.g. Api-version: 2)
  • content type (e.g. Accept: application/vnd.mysuperapi.v2+json)

I will show you how to accomplish each way with hapi and how I ended up coding my own plugin.

URL versioning

This way is very easy to implement in hapi because you just need to change the path of your routes. Here a quick sample how this would look like…

Version 1

    method: 'GET',
    handler: function (request, reply) {

        return reply('Version 1: hello world');

Version 2

    method: 'GET',
    handler: function (request, reply) {

        return reply('Version 2: hello world');

Custom request header and content type

The main difference between the url versioning approach and these two is that request headers are used and there is no sign of a version in the url.

So for example you request the resource /foo/bar and send along a request header specifying the version of the API you want to use – either Api-version: 2 or Accept: application/vnd.mysuperapi.v2+json.

This is also easy to implement and there are some ready to use hapi plugins written to address these cases.

Writing my own plugin

However I could not find any plugin that fully matches my needs and is actively maintained. So I decided to write my own…

You can find it here: hapi-api-version

The plugin is well documented and there is even a sample project if you look at the Github code.

Recent Posts