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
charset is a
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
and then increase it to
v=2 when we make breaking
changes to the representation. To continue our previous
example, we would have
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
v=1 and new clients can just go with
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).