Spring Framework Tutorial 0/19 lessons ~6 min read Lesson 16

    WebClient & HTTP Interfaces

    WebClient is Spring's non-blocking HTTP client from the spring-webflux module.

    Course progress0%
    Focus
    11 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    WebClient is Spring's non-blocking HTTP client from the spring-webflux module. It works in reactive applications and in classic Spring MVC apps, where you can call block() at the edge. Spring 6 adds HTTP interfaces: you declare a Java interface with @GetExchange methods and Spring generates the client.

    For purely blocking code, Spring 6.1 also offers RestClient, a synchronous client with a similar fluent API. RestTemplate still works but is in maintenance mode.

    Purpose of this lesson

    You will configure WebClient with timeouts, map error statuses to domain exceptions, retry transient failures with backoff, call several APIs in parallel, and generate a typed client from an HTTP interface.

    Understanding the topic

    Which client to choose:

    • WebClient — non-blocking; ideal for WebFlux apps and for fanning out several calls in parallel.
    • RestClient (6.1+) — blocking and simple; a good default in Spring MVC apps that make one call at a time.
    • HTTP interfaces — a typed client on top of WebClient or RestClient, generated by HttpServiceProxyFactory.
    • retrieve() turns 4xx/5xx responses into WebClientResponseException unless you map them with onStatus.
    • Timeouts are not set by default — configure connect and response timeouts on the underlying Reactor Netty HttpClient.

    Syntax reference

    HTTP interface client — declare the API, let Spring implement it:

    java
    @HttpExchange("/products")
    public interface CatalogApi {
    @GetExchange("/{sku}")
    Product get(@PathVariable String sku);
    }
    CatalogApi api = HttpServiceProxyFactory
    .builderFor(WebClientAdapter.create(catalog))
    .build()
    .createClient(CatalogApi.class);
    System.out.println("http interface: " + api.get("SKU-2").name());

    Output

    http interface: Mouse

    Register the generated client as a @Bean and inject CatalogApi wherever you need it. The interface is easy to mock in unit tests.

    Production implementation

    Production checklist for outbound HTTP:

    • Create one WebClient per downstream service as a bean and reuse it — it holds the connection pool.
    • Set connect and response timeouts, and an overall timeout() or block(Duration) limit.
    • Retry only idempotent requests (GET, PUT with the same body) and only on transient errors, with backoff and jitter.
    • Map 4xx responses to domain exceptions so callers can tell "not found" from "service down".
    • Propagate tracing headers; in Spring Boot, build clients from the auto-configured WebClient.Builder so observability is applied.

    Informative example

    A catalog client against a local test server (it serves SKU-1 and SKU-2, returns 404 for unknown SKUs, and returns 503 twice before succeeding for FLAKY, counting calls in an AtomicInteger flakyCalls):

    java
    public record Product(String sku, String name, int priceCents) {}
    HttpClient http = HttpClient.create()
    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2_000)
    .responseTimeout(Duration.ofSeconds(3));
    WebClient catalog = WebClient.builder()
    .baseUrl(baseUrl)
    .clientConnector(new ReactorClientHttpConnector(http))
    .defaultHeader("Accept", MediaType.APPLICATION_JSON_VALUE)
    .build();
    Product p = catalog.get().uri("/products/{sku}", "SKU-1")
    .retrieve()
    .bodyToMono(Product.class)
    .block(Duration.ofSeconds(5));
    System.out.println("single: " + p);
    List<Product> both = Flux.just("SKU-1", "SKU-2")
    .flatMap(sku -> catalog.get().uri("/products/{sku}", sku).retrieve().bodyToMono(Product.class))
    .sort((a, b) -> a.sku().compareTo(b.sku()))
    .collectList()
    .block(Duration.ofSeconds(5));
    System.out.println("parallel: " + both.stream().map(Product::name).toList());
    try {
    catalog.get().uri("/products/{sku}", "NOPE")
    .retrieve()
    .onStatus(s -> s.value() == 404, resp -> Mono.error(new ProductNotFoundException("NOPE")))
    .bodyToMono(Product.class)
    .block(Duration.ofSeconds(5));
    } catch (ProductNotFoundException ex) {
    System.out.println("mapped error: " + ex.getMessage());
    }
    Product recovered = catalog.get().uri("/products/{sku}", "FLAKY")
    .retrieve()
    .bodyToMono(Product.class)
    .retryWhen(Retry.backoff(3, Duration.ofMillis(50))
    .filter(ex -> ex instanceof WebClientResponseException w && w.getStatusCode().is5xxServerError()))
    .block(Duration.ofSeconds(5));
    System.out.println("after retries: " + recovered.name() + " (attempts=" + flakyCalls.get() + ")");

    Output

    single: Product[sku=SKU-1, name=Keyboard, priceCents=4999]
    parallel: [Keyboard, Mouse]
    mapped error: No product NOPE
    after retries: Cable (attempts=3)

    flatMap sends both requests concurrently; the explicit sort makes the printed order deterministic. The retry filter only retries 5xx responses — retrying a 404 would just waste time.

    Best practices

    • In Spring MVC apps that make single calls, prefer RestClient; use WebClient when you need concurrency or streaming.
    • Wrap each downstream API behind an HTTP interface or a small client class.
    • Test clients against a local stub server (for example OkHttp MockWebServer or WireMock).

    Common mistakes

    • Calling block() inside a WebFlux request handler — it blocks an event-loop thread and can stall the server.
    • Creating a new WebClient per request and losing connection reuse.
    • No timeouts: one slow dependency ties up threads until the whole service degrades.
    • Retrying non-idempotent POSTs and creating duplicate orders or payments.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    2 questions
    1IntermediateQuestionWebClient, RestClient, or RestTemplate — which do you choose in Spring 6?+

    Answer

    RestClient for straightforward blocking calls in Spring MVC apps; WebClient for reactive apps, streaming, or fanning out concurrent calls; RestTemplate only in existing code, since it is in maintenance mode. HTTP interfaces can sit on top of either RestClient or WebClient.
    2AdvancedQuestionHow do you make outbound HTTP calls resilient?+

    Answer

    Set connect and response timeouts, retry only idempotent requests on transient failures with exponential backoff, map error statuses to domain exceptions, add circuit breakers for failing dependencies, and reuse a pooled client per downstream service.

    Follow-up

    Why must retries be limited to idempotent requests?

    Hands-on exercise

    Hands-on: add a SKU-3 endpoint that sleeps for five seconds. Call it with the client above and confirm the 3-second response timeout fails the call. Then add a fallback with onErrorResume that returns a placeholder Product("SKU-3", "Unavailable", 0).

    Summary

    WebClient is Spring's non-blocking HTTP client and the foundation for HTTP interfaces. Configure timeouts, map errors, retry safely, and use RestClient for simple blocking calls.

    Ready to mark this lesson complete?Track your journey across the entire course.