Introducing RestClient: Spring 6.1's new API to replace RestTemplate
The Spring 6.1 release features the new RestClient
, a synchronous HTTP client that merges the fluent API of WebClient
with the infrastructure of RestTemplate
. This new client is introduced as RestTemplate
is planned to be deprecated in future releases, encouraging developers to transition to more modern solutions. The RestClient
simplifies HTTP interactions while preserving core functionalities like message converters and interceptors, and provides enhanced features for handling responses and managing errors.
For further details, you can read the full blog post here.
Here is just a short comparision between the usage of the RestTemplate
and RestClient
// RestTemplate usage
// GET
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api/resource";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
System.out.println(response.getBody());
// POST
MyObject requestData = new MyObject();
HttpEntity<MyObject> request = new HttpEntity<>(requestData);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
System.out.println(response.getBody());
// RestClient usage
// GET
RestClient restClient = RestClient.builder().build();
String url = "http://example.com/api/resource";
RestClientResponse<String> response = restClient.get(url)
.retrieve(String.class);
System.out.println(response.body());
// POST
MyObject requestData = new MyObject();
RestClientResponse<String> response = restClient.post(url)
.body(requestData)
.retrieve(String.class);
System.out.println(response.body());
Edited by Simon Jakubowski