Sub topic 2
RestClient, RestTemplate and WebClient: which to use
Spring has three HTTP clients that you can use from a Spring Boot application. This chapter explains how they differ and gives you criteria for choosing one. It also shows how to move existing code between them.
It assumes you know:
- Java 17 or later.
- Basic Spring Boot: beans and dependency injection.
- HTTP methods, status codes and headers.
- The difference between blocking and non-blocking code.
The three clients at a glance
All three send HTTP requests and convert JSON to and from Java objects. They differ in programming model, age and dependencies.
- RestTemplate is the original client, introduced in Spring 3. It is synchronous. Its API is a large set of overloaded methods such as
getForObject,postForEntityandexchange. - WebClient arrived in Spring 5 as part of Spring WebFlux. It has a fluent API and is built on Project Reactor, so results come back as
MonoorFluxand the default engine is non-blocking (Reactor Netty). - RestClient was added in Spring Framework 6.1 and is available in Spring Boot 3.2 and later. It is synchronous like RestTemplate and has a fluent API like WebClient.
| Aspect | RestTemplate | WebClient | RestClient |
|---|---|---|---|
| Introduced | Spring 3 | Spring 5 | Spring 6.1 (Boot 3.2) |
| Execution model | Blocking | Non-blocking, reactive | Blocking |
| API style | Many overloaded methods | Fluent | Fluent |
| Return types | Plain objects, `ResponseEntity` | `Mono`, `Flux` | Plain objects, `ResponseEntity` |
| Extra dependency | None | `spring-webflux` and Reactor | None (in `spring-web`) |
| Streaming responses | No | Yes (`Flux`, server-sent events) | No |
| Project status | Maintenance mode | Active | Active, recommended for new blocking code |
Why RestClient exists
RestTemplate works, but its API has grown into dozens of overloads. Each combination of method, URI variables and response type is a separate method. Adding a feature means adding more overloads, so the API is hard to extend.
WebClient has a much better API, but you can only use it comfortably if you accept reactive types. Many teams run ordinary servlet applications and call .block() on every result. That adds a reactive dependency and a mental model they do not need.
RestClient fills this gap. It gives you the WebClient-style fluent chain and returns plain values. It reuses the same infrastructure that RestTemplate uses: HttpMessageConverter instances, ClientHttpRequestFactory implementations and ClientHttpRequestInterceptor implementations. Knowledge you have about RestTemplate configuration carries over.
The same call three ways
Here is a GET of a todo item, written with each client. The Todo record is shared.
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
record Todo(long id, String title, boolean completed) {}
class TodoClients {
private static final String BASE = "https://api.example.com";
// RestTemplate: one overloaded method
Todo withRestTemplate(RestTemplate restTemplate, long id) {
return restTemplate.getForObject(BASE + "/todos/{id}", Todo.class, id);
}
// WebClient: fluent, returns a Mono
Mono<Todo> withWebClient(WebClient webClient, long id) {
return webClient.get()
.uri("/todos/{id}", id)
.retrieve()
.bodyToMono(Todo.class);
}
// RestClient: fluent, returns the value directly
Todo withRestClient(RestClient restClient, long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}
}The WebClient and RestClient chains are nearly identical: get(), uri(), retrieve(), then a body method. The difference is the last step. WebClient hands back a Mono<Todo> that does nothing until something subscribes to it. RestClient blocks the calling thread and returns the Todo.
Deciding which one to use
Work through these questions in order.
Choose WebClient when
- Your application is a WebFlux application and request handling must stay non-blocking. Blocking inside a Netty event-loop thread stalls other requests.
- You need to consume a response as a stream, for example server-sent events or a long
Fluxof items. - You want to compose many remote calls in parallel with reactive operators such as
Mono.zip.
Choose RestClient when
- Your application is a regular servlet-based Spring MVC application.
- You are writing a new client of any kind that can block.
- You want a fluent API without bringing in Reactor.
Keep RestTemplate when
- You have a large working code base and no time to change it.
RestTemplate is in maintenance mode. It still receives bug fixes, but new features go to RestClient, and the Spring team has announced plans to deprecate it formally in a later release. Do not start new code with it.
What about virtual threads?
A common argument for WebClient is that blocking threads are expensive. With virtual threads (Java 21 and later, enabled in Spring Boot 3.2 with spring.threads.virtual.enabled=true), a blocked thread is cheap. A blocking RestClient call parks only a virtual thread, not an operating system thread. For many servlet applications this removes the main performance reason to adopt WebClient. Reactive code is still the right choice for stream-heavy workloads and for applications that are already reactive end to end.
Mixing clients in one application
You can use more than one client. A servlet application may include spring-boot-starter-webflux solely to get WebClient for one streaming endpoint, and use RestClient everywhere else. Adding the WebFlux starter next to the web starter does not turn the application reactive. Spring Boot keeps running it as a servlet MVC application.
You can also build a RestClient on top of an existing RestTemplate. The new client then reuses that template's request factory, message converters, interceptors and error handler.
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
class Bridge {
RestClient fromTemplate(RestTemplate legacyTemplate) {
return RestClient.create(legacyTemplate);
}
}This helps with gradual migration. Shared configuration such as timeouts and authentication stays in one place while you move call sites one at a time.
Migrating from RestTemplate to RestClient
Most RestTemplate calls have a direct RestClient equivalent.
| RestTemplate | RestClient |
|---|---|
| `getForObject(url, T.class, vars)` | `get().uri(url, vars).retrieve().body(T.class)` |
| `getForEntity(url, T.class, vars)` | `get().uri(url, vars).retrieve().toEntity(T.class)` |
| `postForObject(url, body, T.class)` | `post().uri(url).body(body).retrieve().body(T.class)` |
| `postForEntity(url, body, Void.class)` | `post().uri(url).body(body).retrieve().toBodilessEntity()` |
| `put(url, body)` | `put().uri(url).body(body).retrieve().toBodilessEntity()` |
| `delete(url)` | `delete().uri(url).retrieve().toBodilessEntity()` |
| `exchange(..., ParameterizedTypeReference)` | `.retrieve().body(new ParameterizedTypeReference<...>() {})` |
| `setErrorHandler(handler)` | `defaultStatusHandler(...)` on the builder, or `onStatus(...)` per call |
| `RestTemplateBuilder` | `RestClient.Builder` |
Two behaviors are the same as in RestTemplate, which makes migration less risky:
- A 4xx response throws an
HttpClientErrorExceptionsubclass, and a 5xx response throws anHttpServerErrorExceptionsubclass. Both extendRestClientResponseException. Existingcatchblocks for these types keep working. body(...)returnsnullwhen the response has no body, so null handling stays the same as withgetForObject.
One difference to watch for: in the RestTemplate world you often inject a configured RestTemplate bean. For RestClient, Spring Boot auto-configures a RestClient.Builder bean instead, not a ready-made RestClient. The builder bean has prototype scope, so each injection gets a fresh builder. You call build() yourself, usually in a @Configuration class as shown in the next chapter.
One interface, any client
Whichever client you pick, you can hide it behind a declarative interface. Spring's HTTP interface support (@HttpExchange and @GetExchange) has adapters for all three: RestClientAdapter, WebClientAdapter and RestTemplateAdapter. Your service code depends only on the interface, so you can change the client later without touching the callers. A later chapter covers this in detail.
Common mistakes
- Starting new code with RestTemplate out of habit. Search results and older tutorials still show it. Check the date of the source.
- Adding WebFlux only to get a nicer API, then calling
.block()everywhere. RestClient gives you the same fluent API without Reactor. - Expecting RestClient to stream. It reads the full response into the target type, so use WebClient for a
Fluxof events. - Assuming
RestClientis an injectable bean. Only theRestClient.Builderis auto-configured, so you must build the client. - Copying RestTemplate timeout settings without checking. Timeouts live on the request factory, so you must set them again when you build the RestClient, unless you reuse the template with
RestClient.create(restTemplate).
Exercise
A team runs a Spring MVC application on Java 21 with virtual threads enabled. It has 40 RestTemplate calls and needs one new call to a partner API. A second new feature must display a live feed of events pushed by another service as server-sent events. Which client would you use for the new partner call, which for the event feed, and what would you do with the existing 40 calls?
Show answer
Use RestClient for the new partner call. It is a blocking call in a servlet application, and virtual threads make blocking cheap. Use WebClient for the event feed, because only WebClient can consume a response as a stream (a Flux of events), and adding spring-boot-starter-webflux does not make the application reactive. Leave the existing 40 RestTemplate calls working for now. RestTemplate is in maintenance mode but still functions. Migrate them gradually, for example by wrapping the existing template with RestClient.create(restTemplate) so that shared configuration stays in one place.
Exercise
Rewrite this RestTemplate call as a RestClient call: restTemplate.postForObject("/todos", newTodo, Todo.class). What does the call return if the server answers 404, and does that match RestTemplate's behavior?
Show answer
restClient.post().uri("/todos").body(newTodo).retrieve().body(Todo.class). On a 404 response, retrieve() raises an HttpClientErrorException.NotFound, which is a subclass of RestClientResponseException. RestTemplate throws the same exception type, so existing catch blocks keep working.