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
Please enter at least three characters to search
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • 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
  • Secure Spring Boot 3 Application With Keycloak

Trending

  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Scalable, Resilient Data Orchestration: The Power of Intelligent Systems
  • How AI Agents Are Transforming Enterprise Automation Architecture
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  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
Likes (11)
Comment
Save
Tweet
Share
55.5K 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

  • 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
  • Secure Spring Boot 3 Application With Keycloak

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!