Spring applications frequently communicate with external services through HTTP APIs. These integrations may retrieve customer information, submit payments, exchange authentication tokens, or communicate with other microservices. For many years, Spring developers have used RestTemplate to handle these operations.
However, Spring has introduced a more modern HTTP client called RestClient. It provides a fluent API, supports the existing Spring HTTP infrastructure, and makes request construction easier to read and maintain.
With Spring Boot 4.2, the migration has become more important. Spring Framework 7.1 formally deprecates RestTemplate for removal, and Spring Boot 4.2 deprecates its supporting infrastructure in favor of RestClient. This includes RestTemplateBuilder, related customizers, and some testing support.
This does not mean that existing applications must immediately remove every RestTemplate implementation. Teams can migrate gradually, starting with individual service classes and then replacing the underlying configuration.
This article explains the differences between RestTemplate and RestClient, how to configure the new client in Spring Boot 4.2, how to migrate existing HTTP operations, and how to handle authentication, errors, timeouts, and testing.
Understanding RestTemplate and RestClient
Before migrating, it is important to understand how both clients work.
What Is RestTemplate?
RestTemplate is a synchronous HTTP client provided by Spring Framework. It offers methods for making HTTP requests and converting responses into Java objects.
For example, an application can retrieve customer information using getForObject():
RestTemplate restTemplate = new RestTemplate();
Customer customer = restTemplate.getForObject(
"https://api.example.com/customers/101",
Customer.class
);
The method sends a GET request and converts the response body into a Customer object.
RestTemplate also provides methods such as:
- getForObject()
- getForEntity()
- postForObject()
- postForEntity()
- put()
- delete()
- exchange()
- execute()
Although these methods are still familiar to many Spring developers, the API has become feature-complete. Spring now recommends RestClient for synchronous HTTP communication.
What Is RestClient?
RestClient was introduced in Spring Framework 6.1. It is a synchronous HTTP client that uses a fluent API.
Instead of selecting a specific method for every request and response combination, developers build requests through chained method calls.
For example:
RestClient restClient = RestClient.create();
Customer customer = restClient.get()
.uri("https://api.example.com/customers/101")
.retrieve()
.body(Customer.class);
The request is easier to read because the HTTP method, URL, response handling, and target Java type are defined in one chain.
RestClient supports common HTTP methods, headers, cookies, request bodies, message conversion, interceptors, custom request factories, and response handling.
It is still synchronous. If an application requires non-blocking reactive communication, WebClient remains a suitable option.
Why Spring Boot 4.2 Encourages Migration
Spring's HTTP client strategy has evolved over time. RestTemplate remains important in existing applications, but Spring has shifted new development toward RestClient.
The migration timeline is relevant when planning upgrades.
Version | Change |
|---|
Spring Framework 6.1 | Introduced RestClient |
Spring Framework 7.0 | Announced the deprecation direction for RestTemplate |
Spring Framework 7.1 | Formally deprecated RestTemplate for removal |
Spring Boot 4.2 | Deprecated RestTemplate supporting infrastructure in favor of RestClient |
Spring Framework 8.0 | Planned removal of RestTemplate, subject to the framework release schedule |
Spring Boot 4.2 was released in November 2026. Its release notes identify several deprecated components:
RestTemplateAutoConfigurationRestTemplateObservationAutoConfigurationRestTemplateBuilderRestTemplateCustomizerRestTemplateRequestCustomizer- Related testing infrastructure
The recommended replacements include RestClient.Builder, RestClientCustomizer, and updated testing approaches.
The important distinction is that deprecation is not the same as immediate removal. Existing applications can continue using the old client during a controlled migration, but new code should use the recommended API.
Setting Up a Spring Boot 4.2 Project
Start by creating a Spring Boot project with the required web dependency.
For a traditional Spring MVC application, use the Spring MVC starter provided by Spring Boot 4.2.
A Maven dependency example is:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
Use the Spring Boot 4.2 dependency management or parent POM to manage compatible dependency versions.
You do not need to install a separate HTTP client library just to use the basic RestClient API.
Spring Boot provides an auto-configured RestClient.Builder when the required HTTP client infrastructure is available.
Configuring RestClient as a Spring Bean
For a production application, avoid creating a new HTTP client every time a service method executes.
Instead, configure a reusable RestClient bean.
Create a configuration class:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
@Configuration
public class HttpClientConfig {
@Bean
public RestClient customerRestClient(
RestClient.Builder builder) {
return builder
.baseUrl("https://api.example.com")
.defaultHeader(
"Accept",
"application/json"
)
.build();
}
}
Spring Boot provides the builder, allowing the application to use Boot-managed configuration and customizations.
The baseUrl() method defines the default server address. This avoids repeating the same host name in every request.
The defaultHeader() method adds a header to requests made through this client.
The resulting RestClient can be injected into service classes.
Injecting RestClient Into a Service
Create a service class that uses the configured client.
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
@Service
public class CustomerService {
private final RestClient restClient;
public CustomerService(RestClient customerRestClient) {
this.restClient = customerRestClient;
}
public Customer getCustomer(Long id) {
return restClient.get()
.uri("/customers/{id}", id)
.retrieve()
.body(Customer.class);
}
}
Because the base URL is already configured, the service only needs to provide the endpoint path.
This approach keeps HTTP configuration separate from business logic.
Migrating GET Requests From RestTemplate
GET requests are among the most common operations in existing Spring applications.
Consider the following RestTemplate implementation:
RestTemplate restTemplate = new RestTemplate();
Customer customer = restTemplate.getForObject(
"https://api.example.com/customers/{id}",
Customer.class,
101
);
The equivalent RestClient implementation is:
Customer customer = restClient.get()
.uri("/customers/{id}", 101)
.retrieve()
.body(Customer.class);
The migration is straightforward:
RestTemplate | RestClient |
|---|
getForObject()
| get().uri().retrieve().body()
|
getForEntity()
| get().uri().retrieve().toEntity()
|
postForObject()
| post().uri().body().retrieve().body()
|
postForEntity()
| post().uri().body().retrieve().toEntity()
|
put()
| put().uri().body().retrieve()
|
delete()
| delete().uri().retrieve()
|
exchange()
| method().uri().retrieve() or exchange()
|
The fluent API separates request construction from response extraction.
Retrieving Response Headers and Status
Sometimes an application needs more than the response body.
For example, a service may need to inspect the HTTP status code or response headers.
With RestTemplate, developers commonly use getForEntity().
With RestClient, use toEntity():
ResponseEntity<Customer> response = restClient.get()
.uri("/customers/{id}", 101)
.retrieve()
.toEntity(Customer.class);
HttpStatusCode status = response.getStatusCode();
Customer customer = response.getBody();
System.out.println("Status: " + status);
System.out.println("Customer: " + customer);
This is useful when the application needs to process response metadata along with the returned object.
Migrating POST Requests
POST requests usually send data to an external API.
Consider an application that creates a new customer.
The old implementation might look like this:
Customer customer = new Customer(
101L,
"John",
"[email protected]"
);
Customer response = restTemplate.postForObject(
"https://api.example.com/customers",
customer,
Customer.class
);
The equivalent implementation using RestClient is:
Customer customer = new Customer(
101L,
"John",
"[email protected]"
);
Customer response = restClient.post()
.uri("/customers")
.contentType(MediaType.APPLICATION_JSON)
.body(customer)
.retrieve()
.body(Customer.class);
The body() method accepts a Java object. Spring's message converters serialize it into the appropriate request format.
The contentType() method explicitly identifies the request body format.
If the external API returns a status code and headers that the application needs to inspect, use toEntity() instead of body().
For APIs that return no response body, use toBodilessEntity().
Handling PUT and DELETE Requests
PUT and DELETE requests can also be migrated using the fluent API.
PUT Request
A PUT request typically replaces an existing resource.
restClient.put()
.uri("/customers/{id}", 101)
.contentType(MediaType.APPLICATION_JSON)
.body(customer)
.retrieve()
.toBodilessEntity();
The example sends the customer object to the specified endpoint and processes the response without expecting a response body.
DELETE Request
A DELETE request removes an existing resource.
restClient.delete()
.uri("/customers/{id}", 101)
.retrieve()
.toBodilessEntity();
Using toBodilessEntity() makes the intended behavior clear when the application only needs to confirm that the request completed successfully.
If the remote API returns meaningful data after a delete operation, use an appropriate response type instead.
Configuring Headers and Authentication
Many external services require authentication headers, API keys, or custom request headers.
RestClient supports default headers at the client level and individual headers at the request level.
Configuring Default Headers
If every request needs the same API key, configure it in the client:
@Bean
public RestClient paymentRestClient(
RestClient.Builder builder) {
return builder
.baseUrl("https://payments.example.com")
.defaultHeader(
"X-API-Key",
"YOUR_API_KEY"
)
.build();
}
For production applications, do not hardcode API keys in source code. Load them from a secure secret-management service or environment-specific configuration.
Adding Bearer Authentication
When an external API requires a bearer token, add the authorization header:
String token = tokenProvider.getAccessToken();
PaymentResponse response = restClient.post()
.uri("/payments")
.header(
HttpHeaders.AUTHORIZATION,
"Bearer " + token
)
.contentType(MediaType.APPLICATION_JSON)
.body(paymentRequest)
.retrieve()
.body(PaymentResponse.class);
If the token changes frequently, avoid configuring it as a fixed default header during application startup.
Instead, obtain the current token when the request is executed or use a suitable request interceptor.
For more complex OAuth2 client authentication, use Spring Security's OAuth2 client support rather than implementing token lifecycle management manually.
Handling HTTP Errors With RestClient
Error handling is an important part of any HTTP integration.
By default, RestClient.retrieve() applies status handling for 4xx and 5xx responses. These responses normally result in exceptions such as HttpClientErrorException and HttpServerErrorException.
Developers can customize the behavior using onStatus().
For example:
Customer customer = restClient.get()
.uri("/customers/{id}", 101)
.retrieve()
.onStatus(
HttpStatusCode::is4xxClientError,
(request, response) -> {
throw new CustomerNotFoundException(
"Customer request failed: "
+ response.getStatusCode()
);
}
)
.onStatus(
HttpStatusCode::is5xxServerError,
(request, response) -> {
throw new ExternalServiceException(
"Customer service is unavailable"
);
}
)
.body(Customer.class);
The first handler processes client-side HTTP errors. The second handles server-side errors.
In a real application, avoid treating every 4xx response as a missing resource. A 400 response may indicate invalid input, while a 401 or 403 response may indicate an authentication or authorization problem.
Create separate exception types or error mappings where the application needs to distinguish these conditions.
Configuring Default Error Handling
If several service methods share the same error-handling rules, configure a default status handler when building the client.
@Bean
public RestClient customerRestClient(
RestClient.Builder builder) {
return builder
.baseUrl("https://api.example.com")
.defaultStatusHandler(
HttpStatusCode::isError,
(request, response) -> {
throw new ExternalServiceException(
"External API returned "
+ response.getStatusCode()
);
}
)
.build();
}
This avoids repeating the same error-handling logic in every request.
Use request-specific handlers when different endpoints need different business rules.
Configuring Timeouts and HTTP Connections
A reliable HTTP client should have appropriate connection and response timeouts.
Without suitable timeout configuration, a service may wait too long for an external API, affecting application threads and overall response time.
RestClient uses a ClientHttpRequestFactory to create HTTP requests. You can configure this factory according to your application's networking requirements.
For example, a JDK-based request factory can use the JDK HTTP client:
import java.net.http.HttpClient;
import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
@Configuration
public class HttpClientConfig {
@Bean
public RestClient customerRestClient(
RestClient.Builder builder) {
HttpClient httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
JdkClientHttpRequestFactory requestFactory =
new JdkClientHttpRequestFactory(httpClient);
requestFactory.setReadTimeout(
Duration.ofSeconds(15)
);
return builder
.baseUrl("https://api.example.com")
.requestFactory(requestFactory)
.build();
}
}
The connection timeout limits how long the JDK client waits to establish a connection. The request factory's read timeout controls how long it waits for response data according to its implementation.
Timeouts should be based on the external service's expected response time and the application's latency requirements.
For applications that need connection pooling, evaluate an appropriate HTTP client implementation such as Apache HttpComponents and configure its connection pool and timeout settings.
A timeout does not guarantee that the remote server did not process the request. This is especially important for payment, order creation, and other operations that must not be duplicated.
Migrating Existing RestTemplate Configuration
Many Spring Boot applications use RestTemplateBuilder and customizers to configure HTTP clients.
Spring Boot 4.2 deprecates this infrastructure, so developers should migrate it to the new builder and customization APIs.
Replacing RestTemplateBuilder
An older configuration might look like this:
@Bean
public RestTemplate restTemplate(
RestTemplateBuilder builder) {
return builder
.rootUri("https://api.example.com")
.build();
}
The recommended replacement is:
@Bean
public RestClient customerRestClient(
RestClient.Builder builder) {
return builder
.baseUrl("https://api.example.com")
.build();
}
The baseUrl() method replaces the common root URI configuration use case.
Replacing RestTemplateCustomizer
An application may also use a customizer to configure logging or request headers.
With the new client, use RestClientCustomizer.
import org.springframework.boot.restclient.RestClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RestClientConfiguration {
@Bean
public RestClientCustomizer restClientCustomizer() {
return builder -> builder
.defaultHeader(
"X-Application",
"CustomerService"
);
}
}
This allows the application to apply shared configuration to Boot-managed RestClient.Builder instances.
If a client requires a different base URL, authentication mechanism, or timeout configuration, use a dedicated bean or a more specific customizer strategy.
Migrating Gradually From RestTemplate
A complete migration does not need to happen in one release.
Spring Framework supports creating a RestClient from an existing RestTemplate:
RestTemplate restTemplate = new RestTemplate();
RestClient restClient = RestClient.create(restTemplate);
This is useful when an application already has custom HTTP configuration.
The two clients share the underlying HTTP infrastructure, which means existing request factories and interceptors can often be reused.
A practical migration strategy is:
- Identify all
RestTemplate instances and their configurations. - Create a
RestClient from an existing RestTemplate where gradual adoption is needed. - Replace individual service methods with fluent
RestClient requests. - Move shared configuration to
RestClient.Builder. - Replace
RestTemplateCustomizer implementations with RestClientCustomizer. - Update automated tests.
- Remove the old client infrastructure after all dependencies have been migrated.
This approach reduces the risk of changing authentication, serialization, timeout, and error-handling behavior at the same time.
It is especially useful for large applications with multiple external service integrations.
Testing RestClient Integrations
HTTP integrations should be tested without depending on real external services.
Spring provides MockRestServiceServer for testing requests made through RestClient.
A simple test can create a builder, bind the mock server to it, and verify the outgoing request.
import static org.springframework.test.web.client.match
.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response
.MockRestResponseCreators.withSuccess;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
class CustomerServiceTest {
@Test
void shouldRetrieveCustomer() {
RestClient.Builder builder = RestClient.builder();
MockRestServiceServer server =
MockRestServiceServer.bindTo(builder).build();
RestClient client = builder
.baseUrl("https://api.example.com")
.build();
server.expect(
requestTo(
"https://api.example.com/customers/101"
)
)
.andRespond(
withSuccess(
"""
{
"id": 101,
"name": "John"
}
""",
MediaType.APPLICATION_JSON
)
);
Customer customer = client.get()
.uri("/customers/{id}", 101)
.retrieve()
.body(Customer.class);
assert customer != null;
assert customer.getId() == 101;
server.verify();
}
}
This test verifies that the client sends the expected request and correctly converts the response.
For a real Spring Boot 4.2 application, @RestClientTest can provide a focused test context for HTTP client components. Configure the test around RestClient.Builder rather than the deprecated RestTemplateBuilder.
For testing application endpoints and HTTP server behavior, RestTestClient is another option. It provides a fluent testing API and can work with mock transport or a running application, depending on the test configuration.
Keep outbound HTTP client tests separate from controller tests. They validate different parts of the application.
RestClient vs WebClient: Which One Should You Use?
Migrating from RestTemplate does not mean every application should use RestClient.
Spring provides different HTTP clients for different execution models.
Feature | RestTemplate | RestClient | WebClient |
|---|
API style | Template-based | Fluent | Fluent |
Execution | Synchronous | Synchronous | Non-blocking reactive |
Reactive streams | No | No | Yes |
Request construction | Method-based | Chained methods | Chained methods |
Spring recommendation | Deprecated | Recommended for synchronous calls | Recommended for reactive and streaming calls |
Common use case | Existing synchronous applications | Modern synchronous services | High-concurrency reactive applications |
Choose RestClient when the application uses synchronous request-response communication.
Choose WebClient when the application needs non-blocking I/O, reactive streams, or streaming responses.
Do not migrate to WebClient simply because it is newer. A reactive client introduces a different programming model and may not provide a practical benefit for a traditional synchronous service.
Common Migration Mistakes
Assuming RestTemplate Has Been Removed
Spring Boot 4.2 deprecates the supporting infrastructure, but this does not mean every existing application stops working immediately.
Plan the migration based on the framework's removal timeline and your application's upgrade schedule.
Recreating the Client for Every Request
Creating a new RestClient inside every service method is unnecessary.
Build the client once and reuse it. A built RestClient is safe to use across multiple threads.
Losing Existing Interceptors
Applications may use custom interceptors for authentication, request tracing, logging, or correlation IDs.
Review these configurations during migration. Many existing ClientHttpRequestInterceptor implementations can be reused.
Ignoring Timeout Configuration
A client without suitable timeout settings can create long-running requests and reduce application availability.
Configure connection and response timeouts based on the external API's expected behavior.
Assuming Every Error Needs the Same Treatment
A 400 response, 401 response, 404 response, and 503 response represent different conditions.
Map these responses to appropriate application errors instead of converting every failure into one generic exception.
Retrying Non-Idempotent Operations Without Protection
Retrying a POST request after a timeout may create duplicate records or payments if the original request was processed successfully.
Use idempotency keys or other application-level safeguards when repeating an operation could produce side effects.
Testing Only Successful Responses
Tests should also cover authentication failures, validation errors, server failures, empty responses, malformed payloads, and timeouts where appropriate.
Advantages and Disadvantages of RestClient
Advantages
- Provides a modern fluent API.
- Recommended for synchronous HTTP communication in Spring.
- Integrates with Spring message converters.
- Supports request and response customization.
- Works with existing HTTP request factories and interceptors.
- Supports reusable client configuration.
- Provides built-in status handling through
retrieve(). - Supports Boot-managed customization through
RestClientCustomizer. - Offers a gradual migration path from existing
RestTemplate configurations.
Disadvantages
- It remains synchronous and does not provide reactive non-blocking execution.
- Existing applications need migration and regression testing.
- Custom error handling and interceptors may require configuration changes.
- Timeout and connection-pool configuration still require careful planning.
- Teams unfamiliar with fluent APIs may need time to adjust.
- Some legacy
RestTemplate abstractions do not have a direct one-to-one replacement.
Conclusion
Replacing RestTemplate with RestClient is an important modernization step for Spring applications. Spring Boot 4.2 makes this migration more relevant by deprecating the supporting RestTemplate infrastructure in favor of the newer client.
The migration is relatively straightforward for common GET, POST, PUT, and DELETE operations. Developers can use RestClient.Builder for reusable configuration, RestClientCustomizer for shared customization, and MockRestServiceServer for testing outbound HTTP requests.
For large applications, a gradual migration is a sensible approach. Start by replacing individual service integrations, preserve existing request factories and interceptors where possible, and verify that authentication, timeouts, serialization, and error handling continue to work correctly.
The goal is not simply to replace one Java class with another. It is to build a more maintainable HTTP integration layer that follows the direction of modern Spring development while keeping existing application behavior reliable.
Join the conversation! Your thoughts help the community grow.