Sub topic 10
What happens with missing or unsupported versions
This chapter assumes you can configure ApiVersionConfigurer and map methods with the version attribute, as the earlier chapters showed. It covers what Spring MVC does when a request carries no version, a version it cannot parse, or a version it does not support. You will also see how to test these cases and how to shape the error response.
The three failure cases
Before a controller method is chosen, Spring resolves the version from the request, parses it, and checks it against the supported versions. A request can fail at three points.
| Case | Example request | Result |
|---|---|---|
| Missing | No `X-API-Version` header, no default, version required | `MissingApiVersionException`, HTTP 400 |
| Unparseable | `X-API-Version: banana` | `InvalidApiVersionException`, HTTP 400 |
| Unsupported | `X-API-Version: 9.0` when only 1.0 to 2.0 are supported | `InvalidApiVersionException`, HTTP 400 |
Both exceptions implement Spring's ErrorResponse contract, so the default exception resolution turns them into a 400 Bad Request. If you have enabled problem details, the body is an RFC 9457 ProblemDetail.
Missing versions
A request is missing a version when the configured resolver finds nothing. For a header resolver, the header is absent. For a query parameter resolver, the parameter is absent.
The behavior then depends on two settings that interact:
- If you call
setDefaultVersion(...), Spring substitutes that version and the request proceeds. A missing version is no longer an error. - If you set no default, versions are required, and Spring raises
MissingApiVersionException. - If you set no default and call
setVersionRequired(false), the request continues with no version. Mappings that declare aversiondo not match it.
This configuration requires a version and has no default:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ApiVersionConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class StrictApiVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1", "2.0");
}
}A request to /accounts/1 without the header now gets a 400.
The default applies only to absent versions
The default version replaces a missing version only. It does not replace a wrong one. With a default of 1.0, a request carrying X-API-Version: 9.0 still fails. Spring does not quietly fall back, because that would hide client bugs.
Unparseable versions
Spring turns the raw string from the request into a comparable version object through a version parser. The default parser accepts dotted numeric versions such as 1, 1.1 and 2.0, with an optional leading v when you use path segments. A value such as banana or 1..0 cannot be parsed, and the request fails with InvalidApiVersionException.
If you need other formats, such as dates, you can register your own parser with setVersionParser. The same rule applies: whatever your parser rejects becomes an invalid version error, so a parser that throws on bad input gives you the 400 for free.
Unsupported versions
A parsed version must also be one that you support. Supported versions come from two places:
- Versions you declare with
addSupportedVersions(...). - Versions Spring detects from the
versionattributes on your controller mappings. Detection is on by default.
The default version, when you configure one, is also treated as supported.
If the version is well formed but absent from this set, Spring raises InvalidApiVersionException, even if a controller method happens to match it. Declaring versions explicitly is the safer choice. It makes the supported set a deliberate decision in one place instead of a side effect of whatever annotations exist.
A version can be supported without a perfect match
A baseline mapping such as version = "2.0+" accepts 2.0 and any later supported version. The request X-API-Version: 2.1 matches it only if 2.1 is in the supported set. Without that, the request is rejected before mapping is considered. When you add a version to the API, add it to the supported set too.
Path segment versions behave differently
With usePathSegment(1) the version is part of the URL, for example /v2/accounts/1. The segment index tells Spring which path segment holds the version. Your mappings are then written without the version segment, and Spring removes it before matching.
A path that has no version segment does not fit the pattern, so you usually see a 404 for the shifted path instead of a missing version error. Path segment versions are required by nature, so a default version has little effect there. Check this in a test rather than assuming it.
Testing the failure cases
Testing the error paths is as important as testing the happy path. This test class uses the strict configuration above and asserts a 400 for each failure case.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class AccountVersionErrorTests {
@Autowired
MockMvc mockMvc;
@Test
void missingVersionIsRejected() throws Exception {
mockMvc.perform(get("/accounts/1"))
.andExpect(status().isBadRequest());
}
@Test
void unparseableVersionIsRejected() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "banana"))
.andExpect(status().isBadRequest());
}
@Test
void unsupportedVersionIsRejected() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "9.0"))
.andExpect(status().isBadRequest());
}
@Test
void supportedVersionIsAccepted() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "1.0"))
.andExpect(status().isOk());
}
}These tests assume the AccountController from the earlier chapter. If you set a default version in your configuration, missingVersionIsRejected will fail, because the default makes the request valid. That failure is the test doing its job.
Customizing the error response
The built-in response is a bare 400. For clients you often want a message that lists the supported versions. Both exceptions can be handled with a normal @ExceptionHandler in a controller advice.
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.accept.InvalidApiVersionException;
import org.springframework.web.accept.MissingApiVersionException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiVersionErrorAdvice {
private static final String SUPPORTED = "1.0, 1.1, 2.0";
@ExceptionHandler(MissingApiVersionException.class)
ProblemDetail onMissing(MissingApiVersionException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
"Send an X-API-Version header. Supported versions: " + SUPPORTED);
problem.setTitle("API version required");
return problem;
}
@ExceptionHandler(InvalidApiVersionException.class)
ProblemDetail onInvalid(InvalidApiVersionException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST,
ex.getMessage() + " Supported versions: " + SUPPORTED);
problem.setTitle("API version not supported");
return problem;
}
}Hard-coding the list as a constant is fine for a demonstration, but it can drift from the real configuration. In a real service, keep the supported versions in one shared constant or property and use it in both the configurer and the advice.
Should you change the status code?
Some teams prefer 404 or 406 for an unsupported version. 400 is a reasonable default, because the client sent a request the server cannot interpret. If you change it, change it for all clients at once and document it. Clients that branch on the status code will otherwise break.
Common mistakes
- Setting a default version and then expecting a missing version error. The default prevents that error.
- Expecting the default to rescue a bad version. It only covers absent ones.
- Using a baseline mapping such as
"2.0+"and forgetting to add each new version to the supported set. - Testing only success paths, so a configuration change that silently makes versions optional goes unnoticed.
- Returning a different error format for version failures than for other client errors. Use
ProblemDetailconsistently.
Exercise
Your configuration sets setDefaultVersion("1.0") and supports 1.0, 1.1 and 2.0. What status do you expect for (a) a request with no version header, and (b) a request with X-API-Version: 3.0? What changes for (a) if you remove the default?
Show answer
(a) The request succeeds, because the missing version is replaced by the default 1.0. (b) The request fails with 400, because 3.0 is not supported and the default applies only to absent versions. If you remove the default, (a) fails with MissingApiVersionException and a 400, unless you also call setVersionRequired(false).
Exercise
You add a handler with version = "2.0+" and later start sending X-API-Version: 2.1, but clients get a 400. What is the most likely cause, and what is the fix?
Show answer
Version 2.1 is not in the supported set. A baseline mapping matches later versions only if they are supported, and an unsupported version is rejected before mapping. Add 2.1 with addSupportedVersions("2.1") or the equivalent Spring Boot property, in the same change that introduces it.