bodyToMono() extracts a WebClient response body into a Mono of a specified type. For example, a request for one ingredient produces a Mono<Ingredient> that can receive further reactive operations. section 12.4.1
Use bodyToMono() as the final response-extraction step after defining and retrieving a request:
- Call get(), uri(), and retrieve() to construct and execute a GET request. section 12.4.1
- Pass the target class, such as Ingredient.class, so the response becomes a typed Mono<Ingredient>. section 12.4.1
- Apply additional Mono operations before subscribing; without subscription, the request is not sent. section 12.4.1
- Choose bodyToFlux() instead when the response contains multiple items. section 12.4.1
Fetching one ingredient
A complete request can be written as: Mono<Ingredient> ingredient = WebClient.create() .get() .uri("http://localhost:8080/ingredients/{id}", ingredientId) .retrieve() .bodyToMono(Ingredient.class); ingredient.subscribe(i -> { ... }); The returned Mono remains a reactive value until subscription triggers the request. section 12.4.1
Sending and accepting a response
bodyToMono() also handles responses from POST and PUT requests. A POST can send an Ingredient with bodyValue() and decode the returned resource as Mono<Ingredient>. For a PUT with an empty response payload, use bodyToMono(Void.class) and subscribe to the resulting Mono<Void>. section 12.4.2
Mono<Ingredient> ingredient = WebClient.create()
.get()
.uri("http://localhost:8080/ingredients/{id}", ingredientId)
.retrieve()
.bodyToMono(Ingredient.class);
ingredient.subscribe(i -> { ... });
Inspect the compact request chain showing how a URL response becomes a Mono<Ingredient> and starts only after subscription. section 12.4.1
For simple response handling, retrieve() exposes bodyToMono(). When headers or cookies must influence processing, exchangeToMono() provides a ClientResponse first, which can then be mapped to bodyToMono(). section 12.4.5
