Getting started with spring boot WebClient

Kavindu Gayan
2 min readJan 3, 2021

What is WebClient?

You can use WebClient to call REST calls. Traditionally Spring provides RestTemplate to do that, but when comparing to the WebClient it is fully reactive. That means you can send asynchronous non-blocking requests to the remote APIs. So WebClient uses fewer threads and less memory when comparing to the RestTemplate.

If you want to use WebClient, you have to add spring-web flux dependency into your classpath.

The API exposes Reactor is using two types. They are Flux and Mono. Flux is used for handling zero or more results and Mono is used for handling zero or one result.

In the below example, talked about retrieving data from remote API.

First, web flux dependency needs to be added to the pom.xml or to the classpath file.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

Then, the WebClient object needs to be created. for that, WebClient.Builder method can be used. As seen below web client has been created inside the constructor of the class.

private final WebClient webClient;

public WebFluxController(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("http://localhost:8085/datasource").build();
}

Now, the webClient can be used to call REST calls. Let’s see how get the data from APIs. The retrieve() method can be used easily to get the response body.

Getting String

public Mono<String> getString () {
return this.webClient
.get()
.uri("/string")
.retrieve()
.bodyToMono(String.class);
}

Getting Object

public Mono<User> userMono() {
return this.webClient
.get()
.uri("/user")
.retrieve()
.bodyToMono(User.class);
}

Getting Object List

Here Flux is used rather than Mono Since expecting zero or more results.

public Flux<User> userList() {
return this.webClient
.get()
.uri("/user-list")
.retrieve()
.bodyToFlux(User.class);
}

--

--