Versioning REST APIs is a hot topic these days. In this post, I will show you how versioning with a custom Accept header works in Jersey, without going into the politics of which versioning approach is the best. I will build on the project from one of my previous posts on rest.
The idea is to use a custom media type instead of using one of the defined media types such as
application/json. The resource URIs remain unchanged, but a user can ask for different representations of a resource based on media type. Let's define a media type for the blog API as an example:
Now, we can modify our resources to consume and produce these media types:I was pleasantly surprised that Jersey (version 2.6) understands this media type format out of the box. It interprets
+xml clauses correctly and uses existing providers.
When our entities change in a non-compatible way, a new version of the API can co-exist with the first version given that that entity namespace is also changed. The newer API will have its own interface and use an updated media type:
Now the client is required to specify an accept header when using our API. We can remedy this by adding default media types to the latest version of our API. This way, clients invoking the API without an Accept header will be working with the latest version.
And that's it. The complete working maven project can be accessed from GitHub.