34. Calling REST services with ‘WebClient’

If you have Spring WebFlux on your classpath, you can also choose to use WebClient to call remote REST services; compared to RestTemplate, this client has more a functional feel to it and is fully reactive. You can create your own client instance with the builder WebClient.create(), which already provides a good out-of-the-box experience. See the relevant section on WebClient.

Spring Boot will create and pre-configure such a builder for you; for example, client HTTP codecs will be configured just like the server ones (see WebFlux HTTP codecs auto-configuration).

Here’s a typical example:

@Service
public class MyService {

	private final WebClient webClient;

	public MyBean(WebClient.Builder webClientBuilder) {
		this.webClient = webClientBuilder.baseUrl("http://example.org").build();
	}

	public Mono<Details> someRestCall(String name) {
		return this.webClient.get().url("/{name}/details", name)
						.retrieve().bodyToMono(Details.class);
	}

}

34.1 WebClient customization

There are three main approaches to WebClient customization, depending on how broadly you want the customizations to apply.

To make the scope of any customizations as narrow as possible, inject the auto-configured WebClient.Builder and then call its methods as required. WebClient.Builder instances are stateful; any change on the builder will be reflected in all clients subsequently created with it. If you’d like to create several clients with the same builder, you can also consider cloning the builder with WebClient.Builder other = builder.clone();.

To make an application-wide, additive customization to all WebClient.Builder instances, you can declare WebClientCustomizer beans and change the WebClient.Builder as you would do locally at the point of injection.

Lastly, you can fall back to the original API and just use WebClient.create(). In that case, no auto-configuration nor WebClientCustomizer will be applied.