Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

A common concern with REST APIs is how do you version them? The answer is often something like put the version in the beginning of the URI path. But that’s a terrible advice. This prevents you to make small updates to your API, because you need to duplicate everything every time you increase the version.

A good way to version an API is to not do it. Instead, you can version the media types.

Media types accept parameters. The most common example is probably text/html;charset=utf-8. Here, charset is a parameter and utf-8 is the parameter value. It provides extra information about the media types, in this case the encoding used for the text.

The same can be used for versioning the media type. We could very well have a media type with a v=1 parameter, and then increase it to v=2 when we make breaking changes to the representation. To continue our previous example, we would have application/vnd.ninenines.users+json;v=1 and then application/vnd.ninenines.users+json;v=2.

And we can still serve both, of course. We already have the code for it, all we need is to have a separate encoding function per version. Old clients can still request v=1 and new clients can just go with v=2. You can keep a few versions side by side and purge the old ones when clients stop requesting them.

This leaves the question of what should be done when a client tries to request a version of the media type that is not available anymore. A clean way is to detect this (for example by matching on all versions if none of the supported ones matched) and to send back a proper error, with explanations why that is so and how to fix the client (in the case of mobile applications, an upgrade is most likely required).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.