Calling Other APIs: RestTemplate & WebClient

Calling Other APIs: RestTemplate & WebClient in Java: Real services rarely stand alone — they call payment gateways, geocoders, and each other.

Concept Explanation

Real services rarely stand alone — they call payment gateways, geocoders, and each other. Java gives you three reasonable options.

ClientStyleUse when
RestTemplateblockinglegacy code; still everywhere
WebClientnon-blockingnew code, parallel calls
RestClient (Boot 3.2+)blocking, fluentnew 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

  1. No timeouts: The default is wait forever. One hung dependency eventually consumes every request thread — the classic cascading outage.
  2. Building a client per call: Both clients are thread-safe and meant to be shared singletons.
  3. Retrying non-idempotent requests: Retrying a POST /payments can charge the customer twice.
  4. 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

  1. The Timeout: Call an endpoint that sleeps 10 seconds with a 2-second read timeout. Confirm you get ResourceAccessException.
  2. The Parallel Fetch: Use Mono.zip to call two endpoints simultaneously and time it against sequential calls.
  3. The Fallback: Return cached data when the upstream service returns 503.