Sub topic 1
Calling REST APIs with RestClient in Spring Boot
Prerequisites
Assume Java 17 or later, basic Spring Boot knowledge, HTTP fundamentals, and JSON familiarity. This chapter uses Spring Boot 3.2 or later.
What RestClient Is
RestClient is Spring Framework's synchronous, fluent HTTP client. Synchronous means the calling thread waits for the response. Fluent means chained method calls describe the request in readable steps.
It was added in Spring Framework 6.1. A RestClient can send HTTP requests, set headers, serialize request bodies, and convert JSON responses into Java objects.
flowchart LR
A[Java service] --> B[RestClient]
B --> C[HTTP request]
C --> D[REST API]
D --> E[HTTP response]
E --> B
B --> ARestClient, RestTemplate and WebClient: Which to Use
RestTemplate is the older synchronous Spring client. It remains supported, but RestClient provides a more modern API for new synchronous code.
WebClient is a reactive, non-blocking client. It fits applications that already use reactive types such as Mono and Flux, or that need to manage many concurrent requests without blocking threads.
| Client | Execution model | Typical choice |
|---|---|---|
| RestClient | Synchronous and fluent | New blocking applications |
| RestTemplate | Synchronous and older API | Existing code being maintained |
| WebClient | Reactive and non-blocking | Reactive applications |
Choose based on the execution model of your application. Do not select WebClient only because it is newer if the surrounding code is blocking.
Creating and Configuring a RestClient
Spring Boot provides a RestClient.Builder bean. Configure a client with a base URL and headers, then inject the resulting client into a service.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;
@Configuration
class TodoClientConfig {
@Bean
RestClient todoRestClient(RestClient.Builder builder) {
return builder
.baseUrl("https://api.example.com")
.defaultHeader(
HttpHeaders.ACCEPT,
MediaType.APPLICATION_JSON_VALUE)
.build();
}
}The base URL applies to relative request paths. Default headers apply to every request unless a request overrides them.
Building Request URIs
Use URI templates for path variables. RestClient expands and encodes the variables before sending the request.
Todo findById(long id) {
return restClient.get()
.uri("/todos/{id}", id)
.retrieve()
.body(Todo.class);
}A variable passed separately is safer than concatenating strings. It also makes the intended URI structure clear.
Exercise
Which client is the best default for new synchronous Spring Boot code?
Show answer
RestClient. Use WebClient for reactive or non-blocking code, and keep RestTemplate mainly for existing applications.