🌐 What is a REST Client?

AΒ REST Client is used to call another REST API from your Spring Boot app β€” just like your browser makes a request to a website, your app can make requests to other services.


βœ… Common Use Case

Imagine your app needs weather data from another service β€” instead of building your own, you just call a public API using a REST client.


🧰 Types of REST Clients in Spring Boot

  1. RestTemplate (older, still used)
  2. WebClient (modern, reactive and non-blocking)

πŸ’‘ Using RestTemplate (Simple Example)

1. Add Bean in Configuration:

@Bean
public RestTemplate restTemplate() {
Β  Β  return new RestTemplate();
}

2. Use It in Your Service:

@Autowired
RestTemplate restTemplate;

Β 

public String getQuote() {
Β  Β  String url = "https://api.quotable.io/random";
Β  Β  return restTemplate.getForObject(url, String.class);
}

βœ… getForObject() makes a GET request and returns the response as a string (or object).


⚑ Using WebClient (Modern & Non-blocking)

1. Add Dependency (if not already):

<dependency>
Β  Β  <groupId>org.springframework.boot</groupId>
Β  Β  <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2. Example Usage:

WebClient webClient = WebClient.create();

Β 

String response = webClient.get()
Β  Β  .uri("https://api.quotable.io/random")
Β  Β  .retrieve()
Β  Β  .bodyToMono(String.class)
Β  Β  .block();

  • bodyToMono() converts the response to a reactive type.
  • .block() is used to wait and get the result (for non-reactive projects).

πŸ” Bonus: Handling Headers, POST, and Auth

You can easily add headers, POST data, or use auth tokens with both clients.


βœ… Why Use REST Clients?

  • To call external APIs
  • Communicate between microservices
  • Perform GET, POST, PUT, DELETE operations
Back to blog

Leave a comment