Spring Boot: From Basics to Production · Building REST APIs with Spring MVC

Calling Other APIs with RestClient

Make HTTP calls with RestClient, timeouts and error handling.

RestClient (Spring Framework 6.1+) is the modern synchronous HTTP client with a fluent API, replacing most uses of RestTemplate. Build it from the auto-configured RestClient.Builder, set a base URL, default headers and timeouts, and handle error statuses with onStatus. For declarative clients, define an interface with @HttpExchange methods. Use WebClient for reactive code.

@Configuration
class ClientsConfig {
    @Bean
    RestClient ratesClient(RestClient.Builder builder, RatesProperties props) {
        var factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(Duration.ofSeconds(2));
        factory.setReadTimeout(Duration.ofSeconds(5));
        return builder.baseUrl(props.baseUrl()).requestFactory(factory)
                .defaultHeader("Authorization", "Bearer " + props.apiKey())
                .build();
    }
}

@Service
class RatesService {
    private final RestClient client;
    RatesService(RestClient ratesClient) { this.client = ratesClient; }

    BigDecimal rate(String from, String to) {
        return client.get().uri("/rates/{from}/{to}", from, to)
                .retrieve()
                .onStatus(HttpStatusCode::is4xxClientError, (req, res) -> { throw new UnknownCurrency(from, to); })
                .body(RateResponse.class)
                .rate();
    }
}

Common pitfalls

  • No timeouts — a slow dependency ties up request threads.
  • Creating a new client per call.
  • Retrying non-idempotent POSTs blindly.

Key points

  • RestClient for synchronous HTTP
  • Always configure timeouts
  • Map error statuses to domain exceptions

Further reading: Spring: REST clients

Practice questions

Why are timeouts essential for outbound HTTP calls?

Answer

Without them, a hanging dependency blocks request threads indefinitely, eventually exhausting the server's thread pool and causing cascading failures.

What is an @HttpExchange interface?

Answer

A declarative HTTP client: you define an interface with annotated methods, and Spring generates an implementation backed by RestClient/WebClient.

Open in the app to mark lessons complete, take notes and track your progress.