Concept Explanation
Real services rarely stand alone — they call payment gateways, geocoders, and each other. Java gives you three reasonable options.
| Client | Style | Use when |
|---|---|---|
RestTemplate | blocking | legacy code; still everywhere |
WebClient | non-blocking | new code, parallel calls |
RestClient (Boot 3.2+) | blocking, fluent | new blocking code |
RestTemplate
@Configuration
public class HttpConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.setConnectTimeout(Duration.ofSeconds(3))
.setReadTimeout(Duration.ofSeconds(5))
.build();
}
}
@Service
public class RatesClient {
private final RestTemplate http;
public RatesClient(RestTemplate http) { this.http = http; }
public Rate fetch(String currency) {
return http.getForObject(
"https://api.example.com/rates/{cur}", Rate.class, currency);
}
}
Note the placeholder form — never concatenate user input into a URL.
WebClient
@Service
public class WeatherClient {
private final WebClient client;
public WeatherClient(WebClient.Builder builder) {
this.client = builder.baseUrl("https://api.weather.com").build();
}
public Mono<Forecast> forecast(String city) {
return client.get()
.uri("/forecast/{city}", city)
.retrieve() // conceptually
.bodyToMono(Forecast.class)
.timeout(Duration.ofSeconds(5));
}
// Two calls at once instead of one after the other
public Mono<Combined> both(String a, String b) {
return Mono.zip(forecast(a), forecast(b), Combined::new);
}
}
Surviving Failure
An external API will be slow or down. Plan for it:
public Rate fetchSafely(String currency) {
try {
return fetch(currency);
} catch (HttpClientErrorException.NotFound e) {
throw new UnknownCurrencyException(currency); // their 404, your error
} catch (ResourceAccessException e) { // timeout or connection refused
log.warn("Rates service unreachable, using cache", e);
return cache.lastKnown(currency);
}
}
Add @Retryable for transient errors, and a circuit breaker (Resilience4j) so a dead dependency does not exhaust your threads.
Common Mistakes
- No timeouts: The default is wait forever. One hung dependency eventually consumes every request thread — the classic cascading outage.
- Building a client per call: Both clients are thread-safe and meant to be shared singletons.
- Retrying non-idempotent requests: Retrying a
POST /paymentscan charge the customer twice. - Passing their errors through unchanged: Translate them into your own error vocabulary.
Best Practices
- Always set connect and read timeouts — this is the single most important line.
- Wrap each external API in one client class so the URL and error handling live in one place.
- Cache what you can: Exchange rates do not need refetching per request.
- Test with a mock server (WireMock or MockWebServer), never against the live API.
Practice Exercises
- The Timeout: Call an endpoint that sleeps 10 seconds with a 2-second read timeout. Confirm you get
ResourceAccessException. - The Parallel Fetch: Use
Mono.zipto call two endpoints simultaneously and time it against sequential calls. - The Fallback: Return cached data when the upstream service returns 503.