Sub topic 3
Creating and configuring a RestClient
This chapter covers how to build a RestClient and how to set the defaults it applies to every request. It assumes you know Java 17 (records, lambdas), Spring Boot basics (beans, @Configuration, injection), and HTTP methods, status codes, and headers. Sending requests and reading responses come in later chapters. Here the goal is a client that is configured correctly once and then reused.
Three ways to get a RestClient
RestClient is an interface. You get an instance from one of three entry points.
| Entry point | Use it when |
|---|---|
| `RestClient.create()` | You need a quick client with no defaults, such as a script or a spike. |
| `RestClient.create(String baseUrl)` | You only need a base URL. |
| `RestClient.builder()` or an injected `RestClient.Builder` | You need default headers, interceptors, a request factory, or custom message converters. |
The first two are shortcuts that call the builder internally.
import org.springframework.web.client.RestClient;
class Clients {
static RestClient plain() {
return RestClient.create();
}
static RestClient withBaseUrl() {
return RestClient.create("https://api.example.com");
}
}In a Spring Boot application, prefer the builder that Boot provides over RestClient.builder(). The reason is in the next section.
Using the Boot auto-configured builder
With Spring Boot 3.2 or later and spring-boot-starter-web on the classpath, Boot registers a RestClient.Builder bean. It differs from RestClient.builder() in these ways:
- It uses the same HTTP message converters as your MVC application, so your configured Jackson
ObjectMapper(date formats,spring.jackson.*properties, registered modules) also applies to the client. - It picks a request factory based on what is on the classpath, such as Apache HttpClient or the JDK
HttpClient. - It applies every
RestClientCustomizerbean in the context. - It is registered with prototype scope. Each injection point receives a new builder, so calling
baseUrl(...)in one class does not change the builder another class receives.
A RestClient built with RestClient.create() bypasses all of this. A common bug is a client that serializes dates differently from the rest of the application because it was created without the Boot builder.
The configuration below builds a client with a base URL and a default Accept header.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;
@Configuration
class TodoClientConfig {
@Bean
RestClient todoRestClient(RestClient.Builder builder) {
return builder
.baseUrl("https://api.example.com")
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();
}
}Inject the resulting bean into the classes that call the API. A RestClient is immutable and thread-safe once built, so one instance can be shared across threads.
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
@Service
class TodoService {
private final RestClient restClient;
TodoService(RestClient todoRestClient) {
this.restClient = todoRestClient;
}
}One client per remote API
If the application calls more than one remote service, declare one RestClient bean per service. Each has its own base URL, credentials, and timeouts. With several RestClient beans, injection by type is ambiguous. Name each bean and match the constructor parameter name to it, as todoRestClient does above. You can also use @Qualifier.
Builder options for defaults
The builder methods you will use most often are these:
| Method | Effect |
|---|---|
| `baseUrl(String)` | Prefix for every URI template. |
| `defaultHeader(String, String...)` | Header added to every request. |
| `defaultHeaders(Consumer<HttpHeaders>)` | Bulk header changes. |
| `defaultUriVariables(Map<String, ?>)` | Values for template variables used in every URI. |
| `defaultRequest(Consumer<RequestHeadersSpec<?>>)` | Arbitrary per-request defaults, applied to every request before your own settings. |
| `defaultStatusHandler(...)` | Error handling that applies to every call. |
| `requestFactory(ClientHttpRequestFactory)` | The HTTP library and its timeouts. |
| `requestInterceptor(...)` | Code that wraps every request. |
| `messageConverters(Consumer<List<HttpMessageConverter<?>>>)` | Changes to the converters that read and write bodies. |
Some of these have their own chapters: error handling, timeouts, and interceptors. This chapter only places them in the configuration. The next example shows defaultHeaders, defaultUriVariables, and defaultRequest together.
import java.util.Map;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;
class DefaultsExample {
static RestClient build(RestClient.Builder builder) {
return builder
.baseUrl("https://api.example.com/{version}")
.defaultUriVariables(Map.of("version", "v1"))
.defaultHeaders(headers -> {
headers.setAccept(java.util.List.of(MediaType.APPLICATION_JSON));
headers.set("X-Client-Name", "todo-app");
})
.defaultRequest(spec -> spec.header(HttpHeaders.ACCEPT_LANGUAGE, "en"))
.build();
}
}A request such as .uri("/todos/{id}", 7) now goes to https://api.example.com/v1/todos/7. Because defaultUriVariables fills {version}, you pass only id at the call site.
Defaults are defaults
A header set on an individual request is applied on top of the defaults. Before relying on that, check how multi-valued headers such as Accept behave in your Spring version. For a header that must have exactly one value, set it in one place only.
Sharing configuration with RestClientCustomizer
Sometimes you want a setting on every RestClient in the application, such as a tracing header or a shared interceptor. Declare a RestClientCustomizer bean. Boot applies it to the auto-configured builder before you receive it.
import org.springframework.boot.web.client.RestClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
class SharedClientConfig {
@Bean
RestClientCustomizer clientNameCustomizer() {
return builder -> builder.defaultHeader("X-Client-Name", "todo-app");
}
}This example uses the package org.springframework.boot.web.client, which is correct for Spring Boot 3.x. Check the package if you move to a later major version.
Customizers run on the builder before your own configuration method. Settings you apply afterward, such as baseUrl, are added on top. If you call a method that replaces rather than appends, such as requestFactory, your call wins.
Deriving a client with mutate()
A built RestClient cannot be changed, but you can copy it. mutate() returns a builder that starts with all the settings of the existing client. Use it to make a variant that differs in one detail.
import org.springframework.web.client.RestClient;
class MutateExample {
static RestClient adminVariant(RestClient base, String adminToken) {
return base.mutate()
.defaultHeader("Authorization", "Bearer " + adminToken)
.build();
}
}The original client is unchanged. This is useful when several clients share a base URL, converters, and factory but differ in credentials.
Migrating from RestTemplate
If you already have a configured RestTemplate, you can reuse its converters, interceptors, and request factory. This helps when you migrate gradually.
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
class MigrationExample {
static RestClient fromTemplate(RestTemplate restTemplate) {
return RestClient.create(restTemplate);
}
}RestClient.builder(restTemplate) is the builder form of the same idea, for when you want to add more settings. Both copy the template's configuration at the time of the call. Changing the template afterward does not change the client.
Request factory selection and timeouts
The request factory chooses the HTTP library that sends the bytes. Boot picks one automatically, in this order of preference: Apache HttpClient 5, Jetty client, the JDK HttpClient, then the java.net.HttpURLConnection-based factory. Which one you get depends on your dependencies, so adding or removing a library can silently change behavior. If timeouts matter, and they should, set them explicitly.
The default timeouts depend on the factory. Do not rely on them. A client without an explicit read timeout can hold a thread for as long as the server stays silent. The chapter on request factories covers this in detail.
In Spring Boot 3.4 and later you can also set client-wide timeouts with properties, such as spring.http.client.connect-timeout and spring.http.client.read-timeout. These apply to the auto-configured builder. Check your Boot version, because earlier 3.x releases do not have them.
Common errors
- Using
RestClient.create()in a Boot application. The client works but ignores your Jackson configuration and any customizers. InjectRestClient.Builderinstead. - Sharing one builder across beans. The auto-configured builder is prototype scoped, so injection is safe. If you create your own builder bean with
RestClient.builder(), it is a singleton by default, and every call tobaseUrlmutates the same object. Build each client in its own method from its own builder. - Putting secrets in
defaultHeaderfor a client used with several hosts. The header goes to every URL the client calls, including absolute URLs passed touri(...). Keep one client per trusted host. - A base URL with a path and a relative template that lacks a leading slash. Write
.uri("/todos")consistently. Without the slash, joining the path can produce an unexpected URL. - Ambiguous injection. Two
RestClientbeans and a constructor parameter namedrestClientgive aNoUniqueBeanDefinitionException. Name beans and parameters to match, or add@Qualifier.
Exercise
A teammate builds a client in a Spring Boot application with RestClient.create("https://api.example.com"). Responses deserialize, but LocalDate fields in your custom Jackson configuration are parsed differently from the rest of the application. What is the likely cause, and what is the fix?
Show answer
RestClient.create(...) does not use the Boot auto-configured builder, so the client does not pick up the application's configured message converters or ObjectMapper. Inject RestClient.Builder and call builder.baseUrl("https://api.example.com").build() so the Boot converters and any RestClientCustomizer beans apply.
Exercise
You have a todoRestClient bean with a base URL and default Accept header. You need a second client with the same settings plus an Authorization header for admin calls. How do you create it without repeating the base configuration, and does it change todoRestClient?
Show answer
Call todoRestClient.mutate().defaultHeader("Authorization", "Bearer " + token).build(). The mutate() builder starts from the existing client's settings, and the original todoRestClient is unchanged because a built RestClient is immutable.
Exercise
Why can two classes that each inject RestClient.Builder and call baseUrl(...) with different values safely do so in a Boot application?
Show answer
Boot registers the RestClient.Builder bean with prototype scope, so each injection point gets its own new builder. A baseUrl call on one builder does not affect another.