liveBook · Manning

WebClient

As explained in Spring in Action, Sixth Edition

WebClient is a Spring reactive HTTP client API for making asynchronous, nonblocking requests.

WebClient is Spring’s reactive HTTP client for sending and receiving reactive types when communicating with external APIs. Its fluent builder describes the HTTP method, URI, headers, request body, response extraction, and subscription. section 12.4

Build a request through a short sequence:

  • Create or inject a WebClient instance. section 12.4
  • Choose an HTTP method and specify the URI and headers. section 12.4
  • Call retrieve(), then map the response body with bodyToMono() for one value or bodyToFlux() for multiple values. section 12.4.1
  • Subscribe to the resulting Mono or Flux; subscription sends the request and starts data flow. section 12.4.1

Fetching an ingredient

A GET request can fetch one Ingredient by ID and expose it as a Mono<Ingredient>. A collection uses bodyToFlux(Ingredient.class) instead. A shared base URI can be configured on a WebClient bean, allowing injected clients to use relative paths such as /ingredients/{id}. section 12.4.1

Sending resources

Use post() with body() when a Mono supplies the request body, or bodyValue() when a domain object is already available. Use put() for updates; an empty response can be represented with bodyToMono(Void.class). section 12.4.2

Mono<Ingredient> ingredient = WebClient.create()
    .get()
    .uri("http://localhost:8080/ingredients/{id}", ingredientId)
    .retrieve()
    .bodyToMono(Ingredient.class);
 
ingredient.subscribe(i -> { ... });

Follow the complete GET pipeline from WebClient creation through response extraction and subscription. section 12.4.1

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains request construction, response extraction, subscription, base URIs, POST bodies, PUT updates, and timeout handling.
Examples
Demonstrates Taco Cloud ingredient retrieval, collection retrieval, POST creation, PUT updates, and timeout handling.
What it assumes
Assumes familiarity with reactive types such as Mono and Flux while demonstrating their use in HTTP request bodies and responses.
What you can do after
Apply it via WebClient to retrieve, create, and update resources through reactive HTTP requests.
How it connects
Connects WebClient with RestTemplate, Spring WebFlux, Mono, and Flux.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.