Loslegen
Javaneer
Zurück zur Stufe
Modul 2·Web-APIs bauen

Andere APIs aufrufen

HTTP-Dienste mit dem modernen RestClient konsumieren (und wann man zu WebClient greift).

14 Min. LesezeitFortgeschritten

Deutsche Übersetzung in Arbeit

Diese Lektion ist noch nicht ins Deutsche übersetzt und wird daher auf Englisch angezeigt. Der Rest der Seite ist vollständig lokalisiert.

Auf dieser Seite

So far BookVault serves HTTP. Real applications also consume it - calling other services for data. BookVault might enrich a book with cover images or ratings from an external catalog API. Spring's modern tool for this is the RestClient.

RestClient: a fluent, synchronous client

RestClient (introduced in Spring Framework 6.1) offers a clean, chainable API for making HTTP calls and mapping responses straight to Java objects:

@Service
class CoverService {

    private final RestClient client;

    CoverService(RestClient.Builder builder) {          // Boot provides the builder
        this.client = builder.baseUrl("https://covers.example.com").build();
    }

    CoverArt fetchCover(String isbn) {
        return client.get()
            .uri("/covers/{isbn}", isbn)
            .retrieve()                                 // send the request
            .body(CoverArt.class);                      // deserialize JSON -> record
    }
}

The response JSON is deserialized by the same Jackson you already know. Notice you inject a RestClient.Builder - Boot auto-configures it (with sensible timeouts and converters), and you customize per client.

Your app is also a customer

You've been running BookVault's shop - taking orders over the counter. But a shop is also a customer of its suppliers: it phones them to restock. RestClient is your app's phone line to other services: it places the call, waits for the reply, and hands you the goods (a typed object) - using the same wrapping-and-unwrapping (JSON) you use with your own customers.

Handling failures

Remote calls fail - timeouts, 404s, 500s. RestClient lets you handle status codes explicitly instead of letting exceptions surprise you:

CoverArt cover = client.get()
    .uri("/covers/{isbn}", isbn)
    .retrieve()
    .onStatus(status -> status.value() == 404, (req, res) -> {
        throw new CoverNotFoundException(isbn);        // map remote 404 to your domain
    })
    .body(CoverArt.class);

When to reach for WebClient

UseWhen
RestClientStandard synchronous calls - the right default for most apps
WebClientYou need reactive, non-blocking calls (returning Mono/Flux)
RestTemplateLegacy - still works, but prefer RestClient for new code

You'll meet WebClient and the reactive model properly in the Reactive module. For BookVault's blocking, request-per-thread style, RestClient is the natural choice.

Always set timeouts

A remote service that hangs can exhaust your threads and take your app down with it. Configure connect and read timeouts on your RestClient (and consider resilience patterns like retries and circuit breakers, covered in the Microservices module).

Pick the client

For each scenario, choose RestClient or WebClient and say why:

  1. BookVault calls a cover-image API and blocks until it responds, one call per request.
  2. A new gateway service must fan out to dozens of downstream services concurrently without tying up a thread per call.

What is the recommended default client for making synchronous HTTP calls from a Spring app today?

Key takeaways

  • Apps both serve and consume HTTP; RestClient is Spring's modern, fluent, synchronous client for calling other services.
  • Inject the Boot-provided RestClient.Builder, set a base URL, and map responses directly to Java objects via Jackson.
  • Handle remote failures explicitly with onStatus, mapping remote errors to your own domain exceptions.
  • Use WebClient when you need reactive, non-blocking calls; RestTemplate is legacy - prefer RestClient for new code.
  • Always configure timeouts so a hung dependency can't exhaust your threads.
War diese Lektion hilfreich?
Diese Seite auf GitHub bearbeiten