Sub topic 1
What RestClient is
RestClient is Spring's synchronous HTTP client with a fluent API. It arrived in Spring Framework 6.1 and is available in Spring Boot 3.2 and later. This chapter covers what it is, how a request passes through it, and how it relates to the classes you may already know. A working first call at the end shows the basic shape. Later chapters cover URIs, responses, errors, timeouts, interceptors, declarative clients and testing in detail.
Prerequisites
This chapter assumes you already have:
- Java 17 or later, including records and lambdas.
- Basic Spring Boot knowledge: beans,
@Configurationand dependency injection. - HTTP fundamentals: methods, status codes and headers.
- A working idea of JSON as a data format.
You also need a Spring Boot 3.2+ project with spring-boot-starter-web. That starter brings in spring-web, which contains RestClient, and Jackson for JSON conversion.
The problem RestClient solves
Before Spring Framework 6.1, a servlet-based Spring application had two main ways to call another HTTP service:
RestTemplateis blocking and mature. Its API is a large set of overloaded methods such asgetForObject,postForEntityandexchange. It is in maintenance mode, so it gets fixes but no new features.WebClienthas a fluent API, but it lives inspring-webfluxand is built around reactive types (MonoandFlux). Using it for plain blocking calls means adding the WebFlux dependency and calling.block().
Many teams wanted the readable fluent style of WebClient without reactive types and without a second web stack. RestClient fills that gap. It is blocking: the calling thread waits until the response arrives, and the method returns a plain Java object. Its API reads like WebClient, but it runs on the classic infrastructure that RestTemplate uses.
How a call is shaped
Every RestClient call follows the same pipeline. You choose an HTTP method, describe the request, call retrieve() and then pick what to read from the response.
Each stage in the diagram corresponds to a method call on the client:
- The method call (
get(),post(),put(),delete()) starts building a request. uri(...)sets the target. It accepts a URI template with variables, which the client expands and encodes for you.- Optional calls such as
header(...),contentType(...),accept(...)andbody(...)complete the request. retrieve()sends the request and gives you a handle on the response.- A terminal call reads the result.
body(Type)returns the converted body,toEntity(Type)returns aResponseEntitywith status and headers, andtoBodilessEntity()ignores the body.
The request is not sent until retrieve() (or exchange(), covered later) runs. Everything before that only describes the request.
A first working call
The following Spring Boot application calls a public test API at startup and prints the result. It needs only spring-boot-starter-web.
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestClient;
@SpringBootApplication
public class DemoApplication {
public record Todo(long id, String title, boolean completed) {}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
CommandLineRunner firstCall(RestClient.Builder builder) {
return args -> {
RestClient client = builder
.baseUrl("https://jsonplaceholder.typicode.com")
.build();
Todo todo = client.get()
.uri("/todos/{id}", 1)
.retrieve()
.body(Todo.class);
System.out.println(todo);
};
}
}Several things are worth noticing here:
- Spring Boot auto-configures a
RestClient.Builderbean. You inject it and callbuild(), instead of creating a client from nothing. - The API response contains a
userIdfield that theTodorecord does not declare. The Jackson converter thatRestClientregisters by default ignores unknown properties, so this does not fail. body(Todo.class)returns aTododirectly. There is no wrapper type and no.block().- The call runs on the calling thread. If the server is slow, that thread waits.
If you only need a quick client with default settings, RestClient.create() or RestClient.create("https://jsonplaceholder.typicode.com") skips the builder. In a Spring Boot application, prefer the injected builder, because it carries Boot's shared configuration (message converters, observability and any customizers you register).
What is underneath
RestClient is a new API on top of existing components. Knowing which ones helps you predict its behavior:
| Concern | Component | Notes |
|---|---|---|
| Sending HTTP | `ClientHttpRequestFactory` | The same abstraction `RestTemplate` uses. Implementations wrap the JDK `HttpClient`, Apache HttpComponents, Jetty or a simple `HttpURLConnection`. |
| JSON and other formats | `HttpMessageConverter` | The same converters as `RestTemplate` and Spring MVC. Jackson handles JSON when it is on the classpath. |
| Cross-cutting behavior | `ClientHttpRequestInterceptor` | Runs around every request, for example to add authentication headers. |
| URI expansion | `UriBuilderFactory` | Expands templates such as `/todos/{id}` and encodes the values. |
Because the conversion and transport layers are shared, anything you know about message converters or request factories from RestTemplate still applies. The builder chooses a request factory based on what is on the classpath. In a Boot application, you can also configure the factory yourself. The timeouts chapter shows how.
Immutability and thread safety
A built RestClient is immutable and safe to share between threads. Create it once, typically as a bean, and reuse it. The builder, by contrast, is mutable. If you need a variant of an existing client, for example with an extra header, call mutate() on the client. It returns a new builder initialized with the same settings, and the original client stays unchanged.
Errors by default
By default, retrieve() treats a 4xx or 5xx response as an error and throws an exception that extends RestClientResponseException. That exception carries the status code, the response headers and the body. This is the same default RestTemplate has, and it differs from the "return whatever came back" approach of some other clients. The error-handling chapter shows how to map specific statuses to your own exceptions.
Where RestClient fits in the Spring family
You will meet all three clients in real code bases, so it helps to know the difference at a glance. The next chapter compares them in detail.
| Row | `RestTemplate` | `RestClient` | `WebClient` |
|---|---|---|---|
| Programming model | Blocking | Blocking | Non-blocking (reactive), can also block |
| API style | Many overloaded methods | Fluent | Fluent |
| Module | `spring-web` | `spring-web` | `spring-webflux` |
| Status | Maintenance mode | Active, recommended for new blocking code | Active, for reactive code |
| Return types | Plain objects | Plain objects | `Mono` / `Flux` |
If your application is servlet-based and a thread may simply wait for a reply, RestClient is the natural choice for new code. If you already have a large body of RestTemplate code, there is no need to rewrite it at once. RestClient.create(restTemplate) builds a RestClient that reuses the configuration of an existing RestTemplate, so the two can coexist during a gradual move.
A side-by-side comparison
The same request written both ways shows the difference in style:
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
class StyleComparison {
record Todo(long id, String title, boolean completed) {}
Todo withRestTemplate(RestTemplate restTemplate) {
return restTemplate.getForObject(
"https://jsonplaceholder.typicode.com/todos/{id}", Todo.class, 1);
}
Todo withRestClient(RestClient restClient) {
return restClient.get()
.uri("/todos/{id}", 1)
.retrieve()
.body(Todo.class);
}
}The RestTemplate version packs the method, URL, response type and variables into one call, and the overload you pick determines which arguments are allowed. The RestClient version names each step. Adding a header or a body means inserting another call in the chain. You do not search for a different overload.
Common mistakes
- Adding
spring-webfluxjust to useRestClient. It is not needed.RestClientis inspring-web, whichspring-boot-starter-webalready includes. - Creating a new client per request. Building a client repeatedly wastes work and can discard connection pooling. Build it once and inject it.
- Using a Spring Boot version older than 3.2.
RestClientrequires Spring Framework 6.1, so on older versions the class does not exist. - Calling a blocking client on a reactive event loop. In a WebFlux application, a blocking call can stall the event-loop threads. Use
WebClientthere. - Assuming 4xx responses return normally. They throw by default. Code that expects to inspect a 404 body must handle the exception or register an
onStatushandler. - Mixing up the builder and the client. Changing a builder after calling
build()does not affect clients already built from it.
Summary of key ideas
RestClientis a blocking client with a fluent API, added in Spring Framework 6.1 and usable in Spring Boot 3.2+.- A call is a chain: method,
uri, optional headers and body,retrieve(), thenbody()ortoEntity(). - It reuses
ClientHttpRequestFactory,HttpMessageConverterand interceptors from theRestTemplateworld. - A built client is immutable and thread-safe. Share it, and use
mutate()for variants. - 4xx and 5xx responses throw
RestClientResponseExceptionsubclasses by default.
Exercise
A teammate says, "To use RestClient I have to add spring-webflux and call .block() on every result." Is that correct? Explain what RestClient actually needs and what it returns.
Show answer
No. RestClient is part of spring-web, which spring-boot-starter-web already includes, so spring-webflux is not required. It is a blocking client, so body(...) returns the converted Java object directly (for example a Todo) and there is no Mono or Flux to block on.
Exercise
Your application builds a RestClient bean from the injected RestClient.Builder. A colleague wants one call to include an extra header without changing the shared bean. Which method should they use, and why does the shared bean stay unchanged?
Show answer
They should call mutate() on the existing RestClient, add the header on the returned builder and call build() to get a new client. A built RestClient is immutable, so mutate() copies its settings into a fresh builder and the original bean is never modified.
Exercise
A GET call made with RestClient receives a 404 response. With no extra configuration, what happens when you call retrieve().body(Todo.class), and how does this differ from a connection timeout?
Show answer
The call throws an exception that extends RestClientResponseException (HttpClientErrorException for a 404), which carries the status, headers and body. A connection timeout has no HTTP response, so it is reported as a ResourceAccessException instead.