While browsing Hacker News one day, my favorite news site, I came across Stripes versioning blog post. This was not the first time I had come across the idea of using dates to version your APIs, but this time I decided to give it a try.
I’ve commonly seen others suggest simply putting version numbers in the URL to segregate major changes. This can work, but how often are major changes made to your API?
In my experience changes are typically updates to some of the returned data, or additional parameters required for precision. These are small changes but not always backward compatible.
If this happens somewhat often, you’ll be supporting many different versions simultaneously. Not only that, you’ll need to duplicate API endpoints that haven’t changed just to be part of these new versions.
Instead of duplicating the entire API to make some small changes, there is a way of just adding changes to the single endpoint. The following is mainly a proof of concept, but with some modifications it could definitely be a solution.
Using Dates to Access API Versions
So finally, I’ll get right to it. By utilizing the flexibility of the HTTP header we can send the date which our client is able to support. This is done by adding an API-Header with a value of let’s say ‘2017-02-10’.
By sending this date in the header, you’re saying that your client is compatible with all revisions prior to and including this date. If your client will always be up to date, simply use today’s date as the value.
Routing to Specific Versions of APIs
So now that you understand the client side, I’ll explain a little how the API routes the request. Express allows you to create multiple routers with different prefixes. The goal is to generate new routes based on timestamps of when the changes were done.
There is middleware in the express server that extracts the API-Version header value and converts it to a timestamp. The middleware then uses this timestamp to reroute the request to the version compatible with the timestamp. The following image will hopefully help explain.
You may be thinking, what happens when you release versions that don’t include changes to each endpoint. Well, in the same middleware the routing take place, it actually loops through the endpoints to find a matching url, such as ‘fn1’. The routers are obviously sorted in ascending order to match the latest one with the requested API version. But this way, if a version was not updated in the latest release that was requested, the latest updated version will be used.
It may be easier for some just to look at the code, so I’ve put together a quick project and threw it on GitHub. Check out my date-version-api project on GitHub. Let me know what you think.