Thursday, May 8, 2014

Versioning your API

Who has not written or used an API? If you answered no, then this article is not for you and honestly I question how you ended up here. APIs are all the rage these days and everyone has an opinion on what an API should look like. Even more controversial is how do you version your API.

It depends on what you believe.

1. Do you believe in Roy Fielding's REST architecture?
2. Do you believe that accept headers describe how you'd like the resource returned?

If you subscribe to REST (and not Rails version of REST), then you acknowledge that the URL is a permalink to a resource. A location where that resource can always be found. Specifying a version number in that URL suggests that each version is an entirely different resource, not the the same resource presented differently.

And just as the semantics of HTTP verbs make sense, so the semantics of HTTP headers. In the request header I am describing how I want my resource returned. Do I want it returned as XML, JSON, HTML or even a PDF. In addition, maybe I want version 1 of that resource as JSON. This can all be done using the Accept and Version headers of an HTTP request.

(There some arguments for including the version number in your hypermedia type as well. I have not fully subscribed to that approach, but it does make some sense.)

For those of you who have not fully subscribed to RESTful APIs and HATEOAS, I highly recommend taking the time to read through the sites linked below and consider unlearning the older ways of implementing APIs and consider learning why adhering to HATEOAS is important and beneficial.

And honestly, if you didn't believe in separation of concerns, why do you adhere to MVC?


Path to enlightenment

HATEOAS 101 - Brian Mulloy put together a great video presentation of what is HATEOAS
Why build hypermedia APIs - Great review of the why and how of hypermedia in respect to Rails.
Haters gonna HATEOAS - Steve Klabnik explaining the HATEOAS
REST APIs must be hypertext-driven - Fielding himself highlighting what makes up a REST API

For those working in Ruby

Grape - Gem, DSL for describing your API
Roar - Gem, presentation DSL for your resources
Swagger - Document your API
Postman - Chrome extension for testing your API