replace your RestTemplate with RestClient

From the translator

Community Spring IO presents a translation of an article comparing two approaches to interacting with RESTful services in Spring Boot: using the legacy RestTemplate, and the new RestClient. The latter is an add-on to WebClient, and provides a more convenient interface that appeared in Spring Boot 3.2. The article is a fairly superficial comparison of the two approaches, which nevertheless gives a good idea of ​​the new API.

In the world Spring Boot sending HTTP requests to external services is a very common task. Traditionally, developers have relied on RestTemplate to achieve this goal. However, as the Spring Framework evolved, a new and more powerful way to handle HTTP requests emerged: the so-called WebClient. Spring Boot 3.2 introduced us to a WebClient add-on called RestClient.

RestClient offers us more modern and intuitive ways to interact with RESTful services.

Origin of RestTemplate

RestTemplate has been a staple of the Spring ecosystem for many years. This is a synchronous client designed to send HTTP requests and process responses. Using RestTemplate, developers can easily interact with RESTful APIs using familiar syntax Java. However, as applications became more asynchronous and non-blocking, the limitations imposed by RestTemplate became increasingly apparent.

Below is a simple example of using RestTemplate to load data from an external API:

var restTemplate = new RestTemplate(); 

var response = restTemplate.getForObject(
  "https://api.example.com/data", 
  String.class
); 

System.out.println(response);

The emergence of WebClient

With coming Spring WebFlux, an asynchronous, non-blocking web framework, WebClient is born as a modern alternative to RestTemplate. WebClient follows the principles of reactivity and is ideal for developing reactive applications. It supports both synchronous and asynchronous communication, while at the same time offering us a fluent API for composing requests.

Below is an example of using WebClient to perform the same HTTP request as in the previous example:

var webClient = WebClient.create(); 

var response = webClient.get()
  .uri("https://api.example.com/data") 
  .retrieve()
  .bodyToMono(String.class); 

 response.subscribe(System.out::println);

RestClient in Spring Boot 3.2

Release Spring Boot 3.2 included the introduction of RestClient, a high-level abstraction of WebClient. RestClient further simplifies the process of sending HTTP requests, offering a more intuitive fluent API, less boilerplate code, while retaining all the features of WebClient:

Let's look at an example of how RestClient can be used:

var response = restClient 
  .get() 
  .uri(cepURL) 
  .retrieve() 
  .toEntity(String.class); 
 
System.out.println(response.getBody());

With RestClient, the code becomes more concise and easier to read. RestClient independently manages the creation of WebClient instances, eliminating the need for the developer to configure HTTP clients.

Comparing RestClient with RestTemplate

Let's compare RestClient with RestTemplate, using common scenarios as an example:

Initializing an object

RestTemplate:

var response = new RestTemplate();

RestClient:

var response = RestClient.create();

We can also use RestTemplate to create a RestClient:

var myOldRestTemplate = new RestTemplate();             
var response = RestClient.builder(myOldRestTemplate);

GET request

RestTemplate:

var response = restTemplate.getForObject(
  "https://api.example.com/data", 
  String.class
); 

RestClient:

var response = restClient 
  .get() 
  .uri(cepURL) 
  .retrieve() 
  
  .toEntity(String.class);

POST request

RestTemplate:

ResponseEntity<String> response = restTemplate.postForEntity(
  "https://api.example.com/data", 
  request, 
  String.class
); 

RestClient:

ResponseEntity<String> response = restTemplate.postForEntity(
  "https://api.example.com/data", 
  request, 
  String.class
); 

Error processing

RestTemplate:

try { 
  String response = restTemplate.getForObject( 
    "https://api.example.com/data",  
    String.class 
  ); 
} catch (RestClientException ex) { 
  // Handle exception 
} 

RestClient:

String request = restClient.get()  
  .uri( 
    "https://api.example.com/this-url-does-not-exist"
  )  
  .retrieve() 
  .onStatus(
    HttpStatusCode::is4xxClientError, 
    (request, response) -> {  
      throw new MyCustomRuntimeException(
        response.getStatusCode(), 
        response.getHeaders()
      )  
  }
) 
.body(String.class);

As you can see from these examples, RestClient offers a more concise approach to sending HTTP requests compared to RestTemplate.

You can see many other usage examples in the documentation.

Conclusion

Using Spring Boot 3.2 and above, RestClient becomes a modern replacement for RestTemplate, offering a more intuitive and concise way to interact with RESTful services. As an add-on to WebClient, RestClient also addresses the need for reactivity while simplifying the process of sending HTTP requests.


Join the Russian-speaking community of Spring Boot developers in telegram – Spring IOto stay up to date with the latest news from the world of Spring Boot development and everything related to it.

Waiting for everybody, join us!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *