Sub topic 7
Default versions and required versions
This chapter covers what Spring does when a request arrives with no API version. You decide between two policies: assign a default version, or reject the request. The chapter assumes you can write Spring MVC controllers, configure a Spring Boot application with @Configuration classes and application.properties, and read HTTP headers and status codes. It also assumes you have seen the version attribute on @GetMapping and the ApiVersionConfigurer from the earlier chapters.
The question a missing version raises
A version resolver reads the version from the request, for example from the X-API-Version header. Sometimes the request has no such header. The resolver then returns no version, and Spring has to choose one of two behaviors:
- Assign a fixed fallback version and continue (a default version).
- Treat the request as invalid and answer with an error (a required version).
These two policies are mutually exclusive. A default version means requests without a version are acceptable. A required version means they are not.
Why a default version exists
The usual reason for a default is an API that was already live before you introduced versioning. Existing clients send no version header. If you start requiring one, every existing client breaks on the day you deploy.
A default version solves this. You pick the version those unversioned clients were written against and let Spring assign it:
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 ApiVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1", "2.0")
.setDefaultVersion("1.0");
}
}With this configuration:
GET /accounts/1with no header is handled as version1.0.GET /accounts/1withX-API-Version: 2.0is handled as version2.0.
Once Spring has assigned the default, the rest of request handling treats the request exactly as if the client had sent 1.0. The mapping step compares the version attribute of each handler against 1.0. A handler declared with version = "1.0" matches, and so does a baseline handler such as version = "1.0+".
Which version to choose as the default
The default is a compatibility promise to every client that never sent a version. Two choices are common.
| Choice | Effect on unversioned clients | Risk |
|---|---|---|
| Oldest version they were written against (such as `1.0`) | Behavior stays the same when you release new versions | None for them. New clients must send a version to get new behavior. |
| Newest version | Unversioned clients silently receive new response shapes | Clients break when you ship a new version, because the default moves |
Pin the default to a specific old version. Do not treat it as "latest". Changing the default later is itself a breaking change for every client that relies on it. If you must change it, announce it as you would any other breaking change.
Why a required version exists
A default hides client mistakes. A client that forgets to send the header still gets a response, and nobody notices. For an API with no legacy clients, you may prefer to make the version mandatory so that mistakes surface early.
Do this by not setting a default. A missing version is then an error:
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")
.setVersionRequired(true);
}
}The call to setVersionRequired(true) states the intent explicitly. When no default is configured, a version is already required, so the call documents the policy more than it changes it. Writing it down helps the next reader, who will otherwise wonder whether leaving out the default was deliberate.
With this configuration, a request to /accounts/1 with no version header is rejected. Spring raises a missing-version exception, and the default error handling turns it into a 400 Bad Request response. The next chapters on error handling cover how to customize that response.
How the two settings interact
The required flag and the default version describe the same decision from two sides, so they cannot both be on:
| Default version | Version required | Result |
|---|---|---|
| Not set | Not set | Required. A missing version is rejected. |
| Not set | `true` | Required. A missing version is rejected. |
| Set | Not set | Not required. A missing version becomes the default. |
| Set | `true` | Contradiction. Spring rejects this configuration when the application starts. |
The last row is a configuration error, and it shows up at startup rather than at request time. If you see an exception about this combination when the application boots, remove either setDefaultVersion or setVersionRequired(true).
The decision can be drawn as a flow for each incoming request:
What the default does not do
Defaults are easy to over-trust. Four limits are worth knowing.
- It does not rescue unsupported versions. The default applies only when no version was sent. If the client sends
X-API-Version: 9.9and9.9is not in the supported list, the request is rejected as an invalid version. Spring does not substitute the default. - It does not widen the supported set. Keep the default listed in the supported versions, as the examples do, so that the version you assign is one you actually declared.
- It does not apply to handlers without a
versionattribute. A mapping with noversionmatches any request, versioned or not. The default affects only which versioned handlers match. - It matters little with a path segment. If the version is part of the URL, such as
/v2/accounts/1, the request nearly always carries one, so there is usually nothing for the default to fill in. Defaults and required flags matter most for header, query parameter and media type resolvers, where the client can leave the version out.
Setting the default with Spring Boot properties
The simple case needs no Java configuration. The default property sets the same fallback:
spring.mvc.apiversion.use.header=X-API-Version
spring.mvc.apiversion.supported=1.0,1.1,2.0
spring.mvc.apiversion.default=1.0To make the version required through properties, leave spring.mvc.apiversion.default out. The absence of a default is what makes the version required. If you need the explicit setVersionRequired(true) call, use the Java configuration shown earlier. The next chapter on Boot properties compares the two approaches in more detail.
Verifying the policy with tests
A policy that nobody tests drifts. Pin each policy with a small test. This one assumes the default-version configuration above and the AccountController from the previous chapter, which has a 1.0 handler returning a single name field:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class DefaultVersionTests {
@Autowired
MockMvc mockMvc;
@Test
void missingVersionFallsBackToDefault() throws Exception {
mockMvc.perform(get("/accounts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Ada Lovelace"));
}
@Test
void unsupportedVersionIsRejectedEvenWithDefault() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "9.9"))
.andExpect(status().isBadRequest());
}
}The first test proves the fallback reaches the 1.0 handler. The second proves the default does not mask a bad version. If you choose the strict policy instead, replace the first test with a request that expects status().isBadRequest() and a test that sends a valid header.
Choosing a policy
- Choose a default version when the API already has clients that send no version, or when the version is a convenience for most callers. Pin the default to the oldest version those clients target.
- Choose a required version for a new API, or when silent fallback would hide errors. Clients learn immediately that they forgot the header.
- Do not set both. Spring refuses the combination at startup.
Exercise
An API uses the header X-API-Version, supports 1.0, 1.1 and 2.0, and sets 1.0 as the default version. What response does Spring give to a request with the header X-API-Version: 1.5, and what does it give to a request with no version header at all?
Show answer
The request with 1.5 is rejected with a 400 Bad Request as an invalid version, because 1.5 is not in the supported list and the default applies only when no version is sent. The request with no header is handled as version 1.0 and reaches the handlers that match 1.0.
Exercise
A team calls both setDefaultVersion("1.0") and setVersionRequired(true) in their configuration. What happens, and how should they fix it?
Show answer
The two settings contradict each other, because a default means a missing version is acceptable and required means it is not. Spring fails when the application starts. They should keep setDefaultVersion("1.0") if they have legacy clients that send no version, or keep setVersionRequired(true) and drop the default if every client must state a version.