Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 66 ยท Building REST APIs

Calling Other Services (RestClient and HTTP Interfaces)

Call other services from Spring Boot with RestClient and @HttpExchange interfaces: timeouts, retries, error handling, WebClient and MockRestServiceServer.

Modern applications rarely work alone. Your order service asks a payment provider to charge a card, your catalog service asks an inventory service for stock, and your app may call a public API for exchange rates. Each call crosses a network, so it is slower than a method call, it can fail in many ways, and it can hang forever if you let it.

Spring Boot gives you two comfortable ways to make HTTP calls: RestClient, a fluent synchronous client, and HTTP interface clients, where you describe the remote API as a Java interface with annotations and Spring writes the implementation. This lesson shows both, then spends most of its time on what separates a demo from production: timeouts, retries, error handling and testing. The next chapters build on it with Resilience; for the plain JDK client that sits underneath, see HTTP Client in Depth.

Real Spring code is read-only here. The TryIts use the JDK's own java.net.http.HttpClient and a tiny local server on loopback, so you can see timeouts and retries against a real socket.

RestClient

RestClient replaces the older RestTemplate for new code (which is in maintenance mode) and covers what most services need without pulling in the reactive stack. Boot supplies a RestClient.Builder bean, so you create one client per remote service, with its base URL and defaults set once:

Java
@Configuration
class ClientConfig {

    @Bean
    RestClient inventoryClient(RestClient.Builder builder) {
        return builder
            .baseUrl("https://inventory.internal")
            .defaultHeader("Accept", "application/json")
            .build();
    }
}

A call reads like a sentence: choose the method, the URI (with template variables, never string concatenation), then ask for the result:

Java
@Service
class StockService {

    private final RestClient inventory;

    StockService(RestClient inventoryClient) {
        this.inventory = inventoryClient;
    }

    StockLevel stockFor(String sku) {
        return inventory.get()
            .uri("/stock/{sku}", sku)
            .retrieve()
            .body(StockLevel.class);
    }

    void reserve(Reservation reservation) {
        inventory.post()
            .uri("/reservations")
            .contentType(MediaType.APPLICATION_JSON)
            .body(reservation)
            .retrieve()
            .toBodilessEntity();
    }
}

retrieve() executes the call; body(Type) converts the response with the same message converters and Jackson settings as your controllers, as covered in Request and Response Bodies. toEntity(...) gives you the status and headers as well. Passing the SKU as a URI variable means Spring encodes it correctly, so a value containing a slash or a space cannot break the path or inject a different one.

RestClient at a glance

Builder One client per remote service, configured once.
URI templates Variables are encoded for you.
retrieve() Runs the call and converts the body.
Status handlers Turn 4xx and 5xx into your exceptions.
1 / 2

HTTP interface clients

With many endpoints, a pile of restClient.get().uri(...) code gets noisy. An HTTP interface lets you declare the remote API as an interface, much like a Spring Data repository, and Spring generates a proxy that makes the calls:

Java
@HttpExchange("/stock")
interface InventoryApi {

    @GetExchange("/{sku}")
    StockLevel stockFor(@PathVariable String sku);

    @PostExchange("/reservations")
    void reserve(@RequestBody Reservation reservation);

    @GetExchange
    List<StockLevel> lowStock(@RequestParam int below);
}

The annotations mirror the controller ones you already know (@PathVariable, @RequestParam, @RequestBody), which makes the interface self-documenting. You then create the proxy from a RestClient:

Java
@Bean
InventoryApi inventoryApi(RestClient inventoryClient) {
    var factory = HttpServiceProxyFactory
        .builderFor(RestClientAdapter.create(inventoryClient))
        .build();
    return factory.createClient(InventoryApi.class);
}

Spring Framework 7 and Boot 4 add convenience on top of this (registering many interfaces at once with an annotation and configuring them with properties), so check the reference for your release before writing the plumbing by hand. Whichever way you create it, the rest of your code just injects InventoryApi and calls stockFor("A-100"). That is also easy to mock in unit tests, since it is an interface.

What a stand-in shows: a call, a failure and a retry

Network code needs to be tested against a server that misbehaves, which you cannot do against a real payment provider. Our TryIts start a small HTTP server inside the program (on loopback only), then call it with the JDK client that RestClient can use underneath. The first one makes a successful call and an error call, and shows how to turn a status code into a meaningful exception, which is what onStatus handlers do for RestClient.

Java A real HTTP call and status mapping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real RestClient code for the same idea registers the mapping once on the client:

Java
RestClient.builder()
    .baseUrl("https://inventory.internal")
    .defaultStatusHandler(HttpStatusCode::is5xxServerError,
        (request, response) -> { throw new ServiceUnavailableException(response.getStatusCode()); })
    .defaultStatusHandler(status -> status.value() == 404,
        (request, response) -> { throw new StockNotFoundException(); })
    .build();

Without handlers, retrieve() throws Spring's generic HttpClientErrorException (4xx) or HttpServerErrorException (5xx). Translating them into your own exceptions keeps HTTP details out of your domain code, and lets your error handling turn them into clean responses: a remote 503 usually becomes your own 502 or 503, never a leaked copy of the remote body.

Timeouts: the setting you must not skip

By default many HTTP clients wait for a connection or an answer for a very long time, or forever. A slow dependency then ties up one of your threads per request, the thread pool fills up, and your service stops answering even though nothing is wrong with it. Always set two limits:

  • Connect timeout: how long to wait to open the connection (a second or two).
  • Read timeout: how long to wait for the response once connected (a few seconds, matched to what users will tolerate).

Recent Boot versions let you set them with properties, applied to the client factories Boot builds:

YAML
spring:
  http:
    client:
      connect-timeout: 2s
      read-timeout: 5s

You can also set them in code on the request factory you pass to RestClient.builder().requestFactory(...). Which exact property names and classes apply depends on your Boot version, so confirm them against its reference. What does not change is the rule: no outgoing call without limits.

Retries, carefully

A retry fixes transient failures (a dropped connection, a restarting instance) and makes everything worse when used carelessly. Follow four rules:

  1. Retry only safe calls. GET is safe. A POST that creates something is not, unless it carries an idempotency key, as in Designing a Clean API.
  2. Retry only transient errors: connection failures, timeouts and 502/503/504. Never retry a 400 or 404; the answer will not change.
  3. Limit attempts (three is common) and back off between them, with a little random jitter so a crowd of clients does not retry in lockstep.
  4. Budget the total time, or three slow attempts become a user-facing minute.

Spring Framework 7 includes core retry support (@Retryable and a RetryTemplate), and libraries such as Resilience4j add circuit breakers on top; both are covered in Resilience: Timeouts, Retries and Circuit Breakers. The next TryIt shows the bare mechanics against a deliberately flaky local server that fails twice and then succeeds.

Java Retry with backoff against a flaky server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The waits double (20, then 40 ms) so a struggling server gets breathing room; a production version also adds random jitter and stops at a maximum delay. Notice the second run: with only two attempts the call fails, and your code must decide what the user sees (an error, a cached value, or a fallback), which is the topic of the resilience lesson.

WebClient, in one paragraph

WebClient is the non-blocking client from Spring WebFlux. Its API is similar but returns Mono and Flux objects. Choose it when your whole application is reactive, or when you need to stream responses. In a normal Spring MVC service, especially with virtual threads, the blocking RestClient is simpler to write, read and debug, and is the better default.

Testing client code

Never call real services from unit tests: they are slow, flaky and may cost money. Spring offers MockRestServiceServer, which replaces the HTTP layer of a RestClient (or RestTemplate) with a scripted fake:

Java
@RestClientTest(StockService.class)
class StockServiceTest {

    @Autowired StockService stockService;
    @Autowired MockRestServiceServer server;

    @Test
    void readsStockLevel() {
        server.expect(requestTo("/stock/A-100"))
            .andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess("{\"sku\":\"A-100\",\"quantity\":7}", MediaType.APPLICATION_JSON));

        assertThat(stockService.stockFor("A-100").quantity()).isEqualTo(7);
    }

    @Test
    void mapsServerErrors() {
        server.expect(requestTo("/stock/A-100")).andRespond(withServerError());

        assertThatThrownBy(() -> stockService.stockFor("A-100"))
            .isInstanceOf(ServiceUnavailableException.class);
    }
}

The test checks both the request your code sends and how it reacts to a failure, with no network. For the wider testing toolbox, see Test Slices, Context Caching and Test Speed.

Treat every remote response as untrusted input. Validate what you receive, never log tokens or full payloads with personal data, and never follow a redirect or URL from a response blindly. A server-side request that is driven by user-supplied URLs is the classic SSRF vulnerability.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should you pass path values as URI variables (.uri("/stock/{sku}", sku)) instead of concatenating strings?

    URI templates encode each variable, so a value with a slash, a space or a query character stays one path segment instead of changing the URL.
  2. 2. What is an HTTP interface client in Spring?

    With @HttpExchange and related annotations you describe the remote API as an interface, and Spring creates a proxy that uses a RestClient (or other adapter) underneath.
  3. 3. Which calls are safe to retry automatically?

    Retrying is safe when repeating the call has no extra effect and the failure is likely to pass (timeouts, 502/503/504). A 400 will never succeed, and a non-idempotent POST can duplicate work.
  4. 4. Why are timeouts essential on outgoing calls?

    A call that waits forever ties up a thread per request. The pool fills and your service fails because of someone else's slowness.
  5. 5. What does MockRestServiceServer let you do?

    It replaces the HTTP layer of a RestClient or RestTemplate in tests with expectations and canned responses.

Summary

  • RestClient is the fluent, blocking client for new code; build one per remote service from Boot's RestClient.Builder, and use URI templates for variables.
  • HTTP interfaces (@HttpExchange, @GetExchange, and so on) turn a remote API into an injectable Java interface.
  • Translate remote 4xx and 5xx statuses into your own exceptions with status handlers.
  • Always set connect and read timeouts; retry only idempotent calls and transient errors, with limited attempts and backoff.
  • WebClient suits reactive applications; blocking RestClient is the simpler default otherwise.
  • Test client code with MockRestServiceServer, and treat every remote response as untrusted.

Next: Server-Side Views with Thymeleaf.