Video in progress
How do you version a REST API in Spring MVC, and which approach do you choose?
Example / Pro / Con — URL: /api/v2/orders / explicit, easy to cache and log / the URL is no longer just the "resource", it carries the version too; Header: X-API-Version: 2 / clean URL / awkward to try in a browser; Media type: Accept: application/vnd.shop.v2+json / fits HTTP / complex, poorly understood
📖 Answer
| Approach | Example | Pro | Con |
|---|---|---|---|
| URL | /api/v2/orders |
explicit, easy to cache and log | the URL is no longer just the "resource", it carries the version too |
| Header | X-API-Version: 2 |
clean URL | awkward to try in a browser |
| Media type | Accept: application/vnd.shop.v2+json |
fits HTTP | complex, poorly understood |
Spring Framework 7 (Boot 4) has built-in API versioning (@GetMapping(version = "2")). Before that it's done with a URL prefix or headers/produces conditions.
To avoid bumping the version, you need to know what breaks and what doesn't. Adding a new field isn't a breaking change (a client should ignore unknown fields), and neither is a new optional parameter. Removing a field, or renaming it or changing its type, is breaking. Be careful when adding a value to an enum: some clients crash on that.
When a new version ships, keep supporting the old one for a set period (the Deprecation and Sunset headers) and watch a metric for who is still using the old version. Don't duplicate the internal code: separate controllers, a shared service layer, and the only difference in DTOs and mapping.
Sign up to mark studied questions and save your progress.