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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Getting Started With Boot Spring 3.2.0: Building a Hello World REST API With NoSQL Integration
  • Secure Spring Boot 3 Application With Keycloak
  • (Spring) Booting Java To Accept Digital Payments With USDC
  • Spring Boot, Quarkus, or Micronaut?

Trending

  • Minimum Viable Elevator [Comic]
  • Harnessing the Power of SIMD With Java Vector API
  • DSL Validations: Properties
  • Build Your Own Programming Language
  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 user avatar
Fernando Boaglio
·
Feb. 19, 24 · Code Snippet
Like (7)
Save
Tweet
Share
8.6K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Getting Started With Boot Spring 3.2.0: Building a Hello World REST API With NoSQL Integration
  • Secure Spring Boot 3 Application With Keycloak
  • (Spring) Booting Java To Accept Digital Payments With USDC
  • Spring Boot, Quarkus, or Micronaut?

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: