DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Developing Secure REST API Using Spring Boot SSL Bundle Feature
  • Micronaut vs Spring Boot: A Detailed Comparison
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Getting Started With Boot Spring 3.2.0: Building a Hello World REST API With NoSQL Integration

Trending

  • 7 Swift Features That Will Let You Delete Code Tomorrow
  • Avoiding AI Debt as a Team
  • Save To Bookmarks/Favorites
  • Catching Query Regressions Before Your Users Do

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot 3.2: Replace Your RestTemplate With RestClient

Spring Boot 3.2: Replace Your RestTemplate With RestClient

This Spring Boot 3.2 tutorial explores an addition built upon WebClient called RestClient, a more intuitive and modern approach to consuming RESTful services.

By 
Fernando Boaglio
·
Feb. 19, 24 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
71.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In the world of Spring Boot, making HTTP requests to external services is a common task. Traditionally, developers have relied on RestTemplate for this purpose. However, with the evolution of the Spring Framework, a new and more powerful way to handle HTTP requests has emerged: the WebClient. In Spring Boot 3.2, a new addition called RestClient builds upon WebClient, providing a more intuitive and modern approach to consuming RESTful services.

Origins of RestTemplate

RestTemplate has been a staple in the Spring ecosystem for years. It's a synchronous client for making HTTP requests and processing responses. With RestTemplate, developers could easily interact with RESTful APIs using familiar Java syntax. However, as applications became more asynchronous and non-blocking, the limitations of RestTemplate started to become apparent.

Here's a basic example of using RestTemplate to fetch data from an external API:

Java
 
var restTemplate = new RestTemplate();

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

System.out.println(response);

 

Introduction of WebClient

With the advent of Spring WebFlux, an asynchronous, non-blocking web framework, WebClient was introduced as a modern alternative to RestTemplate. WebClient embraces reactive principles, making it well-suited for building reactive applications. It offers support for both synchronous and asynchronous communication, along with a fluent API for composing requests.

Here's how you would use WebClient to achieve the same HTTP request:

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

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

 

Enter RestClient in Spring Boot 3.2

Spring Boot 3.2 brings RestClient, a higher-level abstraction built on top of WebClient. RestClient simplifies the process of making HTTP requests even further by providing a more intuitive fluent API and reducing boilerplate code. It retains all the capabilities of WebClient while offering a more developer-friendly interface.

Let's take a look at 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 readable. The RestClient handles the creation of WebClient instances internally, abstracting away the complexities of setting up and managing HTTP clients.

Comparing RestClient With RestTemplate

Let's compare RestClient with RestTemplate by looking at some common scenarios:

Create

RestTemplate:

var response = new RestTemplate();


RestClient:

var response = RestClient.create();


Or we can use our old RestTemplate as well:

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


GET Request

RestTemplate:

Java
 
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:

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


RestClient:

var response = restClient
        .post()
        .uri("https://api.example.com/data")
        .body(request)
        .retrieve()
        .toEntity(String.class);


Error Handling

RestTemplate: 

Java
 
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 seen in these examples, RestClient offers a more streamlined approach to making HTTP requests compared to RestTemplate.

Spring Documentation gives us many other examples.

Conclusion

In Spring Boot 3.2, RestClient emerges as a modern replacement for RestTemplate, offering a more intuitive and concise way to consume RESTful services. Built on top of WebClient, RestClient embraces reactive principles while simplifying the process of making HTTP requests. 

Developers can now enjoy improved productivity and cleaner code when interacting with external APIs in their Spring Boot applications. It's recommended to transition from RestTemplate to RestClient for a more efficient and future-proof codebase.

API REST resttemplate Spring Boot

Opinions expressed by DZone contributors are their own.

Related

  • Developing Secure REST API Using Spring Boot SSL Bundle Feature
  • Micronaut vs Spring Boot: A Detailed Comparison
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Getting Started With Boot Spring 3.2.0: Building a Hello World REST API With NoSQL Integration

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook