Sub topic 1
Why and When to Version an API
Prerequisites
Assume you can build Spring MVC REST controllers, use @RestController and @GetMapping, configure Spring Boot properties, and understand HTTP headers, query parameters, and status codes.
An API version is a named contract between a server and its clients. Create a new version when a change can break an existing client. Removing a response field, changing its type, renaming a request field, or changing required behavior usually needs a new version. Adding an optional response field is often compatible and does not need one.
Versioning lets old clients continue working while newer clients adopt a changed contract.
Choosing a Versioning Strategy
Spring can read a version from several parts of an HTTP request:
| Strategy | Example | Main trade-off |
|---|---|---|
| Header | `X-API-Version: 2.0` | Keeps URLs stable, but is less visible |
| Path segment | `/v2/accounts/1` | Easy to see and cache, but changes URLs |
| Query parameter | `/accounts/1?version=2.0` | Easy to try, but can be inconsistently handled |
| Media type parameter | `Accept: application/json;version=2.0` | Uses content negotiation, but is harder to understand |
Choose one strategy for an API unless you have a clear compatibility reason to support more than one. Header versioning is a useful default when resource URLs should remain stable.
Enabling Versioning with ApiVersionConfigurer
Implement WebMvcConfigurer and configure an ApiVersionConfigurer. This example reads X-API-Version, accepts three versions, and uses 1.0 when the request omits the header.
@Configuration
public class ApiVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1", "2.0")
.setDefaultVersion("1.0");
}
}The supported-version list is important. It defines which values Spring can resolve and match. A default version makes an unversioned request predictable. You can instead require every request to provide a version when accidental fallback would be unsafe.
Reading Versions from Requests
The resolver determines where Spring reads the version. Use the corresponding configuration method for a path segment, query parameter, or media type parameter when your API uses those forms. The controller mappings then use the resolved value rather than manually inspecting the request.
For example, a header request selects a version like this:
GET /accounts/1 with X-API-Version: 2.0
Spring resolves 2.0, then chooses the controller mapping declared for that version.
Exercise
Which strategy keeps /accounts/1 unchanged while allowing clients to request version 2.0?
Show answer
Header versioning, such as X-API-Version: 2.0.