Sub topic 11
Calling a versioned API with RestClient
This chapter covers the client side of API versioning. Earlier chapters configured the server to read a version from a request. Here you configure RestClient to send that version, so calling code names a version and never builds headers by hand. It assumes you can write a Spring MVC controller, you know what a request header and a query parameter are, and you have used RestClient for a basic call. It also assumes the server from the earlier chapters is running with header-based versioning on X-API-Version, supported versions 1.0, 1.1 and 2.0, and a default of 1.0.
Why the client needs version support
Without client support, every call site that wants version 2.0 has to set a header itself:
client.get().uri("/accounts/1").header("X-API-Version", "2.0")This works, but it spreads the transport detail (header name, query parameter name, path position) across the code base. If the server later moves from a header to a path segment, every call site changes.
Spring Framework 7 moves that detail into one place. You give the client builder an ApiVersionInserter, which knows where the version goes in a request. Each call then supplies only the version value. The client also stays close to the server configuration, because both sides describe the same choice: the header name, the query parameter or the path position.
The two pieces: inserter and version value
Two things work together:
- An
ApiVersionInserteris configured once on the builder. It writes the version into the outgoing request. - A version value is supplied per request with
apiVersion(...), or once for all requests withdefaultApiVersion(...)on the builder.
The version value is an Object. You can pass a String such as "2.0", or any object whose string form is the version. A formatter converts the value to the text that goes on the wire. By default that is the value's toString().
The diagram block must follow the required format, so here it is in full:
A complete client
The next example builds a client, calls version 1.0 and version 2.0 of the same URL, and prints both results. It uses RestClient directly, so it needs only spring-web and Jackson on the classpath.
import org.springframework.web.client.ApiVersionInserter;
import org.springframework.web.client.RestClient;
public class AccountClientDemo {
record AccountV1(long id, String name) {}
record AccountV2(long id, String firstName, String lastName) {}
public static void main(String[] args) {
RestClient client = RestClient.builder()
.baseUrl("http://localhost:8080")
.apiVersionInserter(ApiVersionInserter.useHeader("X-API-Version"))
.build();
AccountV1 v1 = client.get()
.uri("/accounts/{id}", 1)
.apiVersion("1.0")
.retrieve()
.body(AccountV1.class);
AccountV2 v2 = client.get()
.uri("/accounts/{id}", 1)
.apiVersion("2.0")
.retrieve()
.body(AccountV2.class);
System.out.println(v1);
System.out.println(v2);
}
}Both requests use the same URI. Only the apiVersion value differs, and the response shape follows it. The response type is the caller's choice. RestClient does not check that AccountV2 matches what version 2.0 returns, so a mismatch shows up as missing or null fields at runtime.
Setting a default version on the client
If most calls use one version, set it on the builder:
import org.springframework.web.client.ApiVersionInserter;
import org.springframework.web.client.RestClient;
RestClient client = RestClient.builder()
.baseUrl("http://localhost:8080")
.apiVersionInserter(ApiVersionInserter.useHeader("X-API-Version"))
.defaultApiVersion("2.0")
.build();A call that does not set apiVersion now sends 2.0. A call that does set it overrides the default for that request only. Pinning a client default is a good habit. It makes the client independent of the server's default version. If the server team later changes its default from 1.0 to 1.1, a client that never named a version would change behaviour without any change on its side.
A client default and a server default solve different problems:
| Setting | Where it lives | What it controls |
|---|---|---|
| `setDefaultVersion` or `spring.mvc.apiversion.default` | Server | The version assumed when a request carries none |
| `defaultApiVersion` | Client builder | The version the client sends when a call names none |
Choosing where the version goes
The inserter you pick must match the resolver on the server. A header inserter paired with a query-parameter resolver sends a version the server never looks at, and the server falls back to its default or rejects the request.
| Server resolver | Client inserter | Resulting request |
|---|---|---|
| Request header | `ApiVersionInserter.useHeader("X-API-Version")` | `X-API-Version: 2.0` |
| Query parameter | `ApiVersionInserter.useQueryParam("version")` | `/accounts/1?version=2.0` |
| Path segment | `ApiVersionInserter.usePathSegment(0)` | The version becomes the first path segment |
| Media type parameter | `ApiVersionInserter.useMediaTypeParam(...)` | A parameter on the media type header |
For a query parameter, the builder call changes in one place only:
import org.springframework.web.client.ApiVersionInserter;
import org.springframework.web.client.RestClient;
RestClient client = RestClient.builder()
.baseUrl("http://localhost:8080")
.apiVersionInserter(ApiVersionInserter.useQueryParam("version"))
.build();The call sites stay the same, which is the point of the inserter. Switching transports is a one-line change in the builder.
Formatting the version value
The text sent on the wire comes from the version object. If your server expects the exact text 2.0, pass "2.0". You can also pass a small type of your own and keep version names out of string literals:
public enum AccountApi {
V1("1.0"), V2("2.0");
private final String text;
AccountApi(String text) {
this.text = text;
}
@Override
public String toString() {
return text;
}
}With this enum, apiVersion(AccountApi.V2) sends 2.0, because the default formatting uses toString(). A typo such as "2.O" becomes a compile error instead of a request the server rejects. If you need different text on the wire, such as a v prefix, register an ApiVersionFormatter on the builder with apiVersionFormatter(...) instead of overriding toString().
When the client and server disagree
The client does not validate the version. It sends what you give it, and the server decides what to do. Three outcomes are common:
- Supported version. The server picks the matching handler, and you get a normal response.
- Unsupported version. The server returns a client error, usually 400 Bad Request, for a version outside its supported list.
- No version sent. The server uses its default version, or returns an error if versions are required.
With retrieve(), a 4xx response throws a RestClientResponseException subclass such as HttpClientErrorException.BadRequest. You can catch it and read the status and body:
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClient;
public class VersionErrorDemo {
public static void main(String[] args) {
RestClient client = RestClient.builder()
.baseUrl("http://localhost:8080")
.defaultHeader("Accept", "application/json")
.build();
try {
client.get()
.uri("/accounts/1")
.header("X-API-Version", "9.9")
.retrieve()
.body(String.class);
} catch (HttpClientErrorException e) {
System.out.println("Status: " + e.getStatusCode());
System.out.println("Body: " + e.getResponseBodyAsString());
}
}
}This example sets the header by hand on purpose. It shows what a rejected version looks like without the inserter in the way.
Reading deprecation signals
A server can mark an old version as deprecated with response headers. The Deprecation and Sunset headers are the usual ones. The client can read them without changing how it reads the body. toEntity gives you the headers along with the body:
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.ApiVersionInserter;
import org.springframework.web.client.RestClient;
public class DeprecationCheck {
public static void main(String[] args) {
RestClient client = RestClient.builder()
.baseUrl("http://localhost:8080")
.apiVersionInserter(ApiVersionInserter.useHeader("X-API-Version"))
.build();
ResponseEntity<String> response = client.get()
.uri("/accounts/1")
.apiVersion("1.0")
.retrieve()
.toEntity(String.class);
String sunset = response.getHeaders().getFirst("Sunset");
if (sunset != null) {
System.out.println("Version 1.0 is retiring on: " + sunset);
}
}
}Logging a warning when Sunset appears gives you an early notice in your own logs, long before the server drops the version.
WebClient
WebClient follows the same model. Its builder accepts an ApiVersionInserter, and its request specs accept apiVersion(...). The reactive chain around it is unchanged. The inserter and the version value are the same two pieces described above.
Common mistakes
- Inserter and resolver do not match. The client puts the version in a header and the server reads a query parameter. Requests succeed but always get the server's default version.
- Relying on the server default. The client never names a version, so a server-side change of default silently changes the client.
- Hardcoded strings spread through the code. A typo reaches the server and comes back as a 400. Use a constant or an enum.
- Assuming the response type matches. The version controls which handler runs, not which Java type your client uses to read the result.
Exercise
Your server resolves the version from the query parameter version. A teammate builds the client with ApiVersionInserter.useHeader("X-API-Version") and calls apiVersion("2.0"). Every response comes back in the version 1.0 shape, which is the server default. Why, and what is the fix?
Show answer
The client puts 2.0 in a header, but the server only reads the version query parameter. It finds no version in the request and falls back to its default, 1.0. The request is not rejected, because a missing version is allowed when a default exists. The fix is to make both sides use the same transport. On the client, use ApiVersionInserter.useQueryParam("version"), or change the server to read the X-API-Version header. Setting defaultApiVersion("2.0") on the client builder alongside the correct inserter also keeps calls from depending on the server default.
Exercise
Why does the chapter suggest setting defaultApiVersion on the client even when the server already has a default version?
Show answer
The two defaults answer different questions. The server default decides what happens when a request carries no version, and the server team can change it. A client that sets its own default always sends an explicit version, so a server-side change of default does not alter the client's behaviour.