Video in progress
How do you write an HTTP call from one service to another in Spring Boot 3?
Usually you use RestClient (Spring 6.1+) or WebClient, and for a declarative style an @HttpExchange interface or OpenFeign. RestTemplate still works, but RestClient is recommended for new code.
📖 Answer
RestClient is synchronous, with a fluent API, and is the modern replacement for RestTemplate:
@Configuration
class ClientsConfig {
@Bean
RestClient paymentRestClient(RestClient.Builder builder) {
return builder.baseUrl("http://payment-service")
.build();
}
}
@Service
class PaymentClient {
private final RestClient client;
PaymentClient(RestClient paymentRestClient) {
this.client = paymentRestClient;
}
PaymentDto get(long id) {
return client.get()
.uri("/api/payments/{id}", id)
.retrieve()
.body(PaymentDto.class);
}
}
A few things to note:
- Spring Boot provides the
RestClient.Builderitself, and if you inject it, tracing and metrics get wired in automatically. If you create it by hand withRestClient.create(), you may lose that. retrieve()throws an exception on a 4xx/5xx response; how you handle it is up to you.- Be sure to configure timeouts; we can talk about that separately.
In a reactive stack (WebFlux) you use WebClient instead.
Sign up to mark studied questions and save your progress.