Thursday, February 23, 2023

10 Examples of WebClient In Spring Framework and Java

Hello guys, if you are wondering how to use WebClient on Spring Framework and looking for simple how to examples of WebClient then you have come to the right place. Earlier, I have shared 10 example of RestTemplate in Spring Framework and in this article, I Am going to share 10 example of WebClient in Spring. These examples covers everything from sending GET request to REST API and consuming response, and also sending POST, PUT, and PATCH request to RESTful Web Services. You will also learn how to set header like Basic Authentication and Authorization header, cookies and much more.  


But, before we get to the 10 best examples that will teach you everything there is to know about the Spring WebClient in Java, let me tell you a little bit more about what it really is. 

The Spring WebClient is basically a reactive and non-blocking web client that can perform HTTP requests. It is aimed at providing a functional and fluent API style and was added to Spring 5.


 


10 Examples Of Spring 5 WebClient In Java

Before Spring 5, the RestTemplate had been the main technique used for client-side HTTP accesses. It is part of the Spring MVC project. But these days, WebClient is the most efficient approach. 

Before using the WebClient API, you should import the spring-boot-starter-webflux module into your project. You can do this easily:

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-webflux</artifactId>

</dependency>

In this list, we have compiled 10 examples of the Spring WebClient that will teach you everything you need to know about this innovative approach. 


1. Creating And Configuring The WebClient

There are many different ways to create WebClient. You can use any of these approaches.
You can use the create() method which is basically an overloaded method. It can accept a base URL for requests.

WebClient webClient1 = WebClient.create();

WebClient webClient2 = WebClient.create("https://client-domain.com");

Additionally, you can also use WebClient.Builder API. 

WebClient webClient2 = WebClient.builder()
        .baseUrl("http://localhost:3000")
        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .build();

2. How To Send Requests

If you want to send a request, you can use the fluent API and then execute the necessary steps. For example, if you want to send an HTTP POST request, you should first create WebClient.UriSpec using any of the prebuilt methods. 

Then, you need to set the required URL. You can also set the request headers and the authentication details. You can also set the request body. 

See the following example to get a better understanding:

WebClient webClient = WebClient.create("http://localhost:3000");

Employee createdEmployee = webClient.post()
		.uri("/employees")
		.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
		.body(Mono.just(empl), Employee.class)
		.retrieve()
		.bodyToMono(Employee.class);

3. How To Handle Responses

Here you can use the method exchange() which can return the CLientResponse. It will have all the response elements like status and headers. An important thing to remember is that when you are using the exchange() method you should always use the body or toEntity methods to make sure that the resources are released correctly. 



4. WebClient: GET API

You will most commonly use the GET API for fetching a collection of resources or even a single resource. Check out the following example to get a better example:

Autowired
WebClient webClient;

public Flux&lt;Employee&gt; findAll() {
	return webClient.get()
		.uri("/employees")
		.retrieve()
		.bodyToFlux(Employee.class);
}

public Mono&lt;Employee&gt; findById(Integer id)
{
	return webClient.get()
		.uri("/employees/" + id)
		.retrieve()
		/*.onStatus(httpStatus -&gt; HttpStatus.NOT_FOUND.equals(httpStatus),
                clientResponse -&gt; Mono.empty())*/
		.bodyToMono(Employee.class);
}





5. WebClient: POST API

The POST API can be used for creating a particular resource. You can see the following example of the post() method for creating an employee:

@Autowired
WebClient webClient;

public Mono&lt;Employee&gt; create(Employee empl){
	return webClient.post()
		.uri("/employees")
		.body(Mono.just(empl), Employee.class)
		.retrieve()
		.bodyToMono(Employee.class);
}


6. WebClient: PUT API

You can use the PUT API for updating a resource. You can check out the following example of the put() method for updating an employee. Please note that the HTTP PUT /employees/{id} will update existing employee data from the request body. It will also return the updated employee. 

@Autowired
WebClient webClient;

public Mono&lt;Employee&gt; update(Employee e){
	return webClient.put()
		.uri("/employees/" + e.getId())
		.body(Mono.just(e), Employee.class)
		.retrieve()
		.bodyToMono(Employee.class);
}

7. WebClient: DELETE API

The DELETE API is most commonly used for deleting a resource. In the following example, the delete() method is used for deleting an employee from the records. You can see that the HTTP DELETE /employees/{id} will delete an existing employee along with its ID. It will not accept any request body. It will also not return any response body. 

@Autowired
WebClient webClient;

public Mono&lt;Void&gt; delete(Integer id){
	return webClient.delete()
		.uri("/employees/" +id)
		.retrieve()
		.bodyToMono(Void.class);
}

8. Understanding Memory Limit

The Spring WebFlux will configure the default memory limit for buffering data. It will be set to 256 kb. If you exceed this limit, then you will encounter the DataBufferLimitException error. You can also easily reset the memory limit by configuring the property given below in the application.properties file. 

spring.codec.max-in-memory-size=1MB



9. The Connection Timeout

You can also use the HttpClient class for setting the timeout periods for connection timeout, read timeout, as well as write timeouts. 
Check out the following example:

@Bean
public WebClient getWebClient(){
	HttpClient httpClient = HttpClient.create()
	        .tcpConfiguration(client -&gt;
	                client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
	                .doOnConnected(conn -&gt; conn
	                        .addHandlerLast(new ReadTimeoutHandler(10))
	                        .addHandlerLast(new WriteTimeoutHandler(10))));

	ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);	    

	return WebClient.builder()
	        .baseUrl("http://localhost:3000")
	        .clientConnector(connector)
	        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
	        .build();
}

9. How To Pass The Request Body In WebClient Requests

In case you have the request body in the form of a Mono or Flux, you can easily pass it to the body() method in WebClient. You can also just create a Mono or Flux from an object. See the following example to get a better understanding:

public Mono<GithubRepo> createGithubRepository(String username, String token, 
    RepoRequest createRepoRequest) {
    return webClient.post()
            .uri("/user/repos")
            .body(Mono.just(createRepoRequest), RepoRequest.class)
            .header("Authorization", "Basic " + Base64Utils
                    .encodeToString((username + ":" + token).getBytes(UTF_8)))
            .retrieve()
            .bodyToMono(GithubRepo.class);
}



10. How To Add A Basic Authentication Using A Filter Function

The ExchangeFilterFunction API will give you a filter for basic authentication. You can use it easily. Check out the following example:

WebClient webClient = WebClient.builder()
        .baseUrl(GITHUB_API_BASE_URL)
        .defaultHeader(HttpHeaders.CONTENT_TYPE, GITHUB_V3_MIME_TYPE)
        .filter(ExchangeFilterFunctions
                .basicAuthentication(username, token))
        .build();



Spring 5 Web Client Frequently Asked Questions

Now, let's answer frequently asked questions about Spring 4 Web Client like what they are, how to use them and any difference between WebClient and RestTemplate in Spring


1. What exactly is the Spring WebClient?

The Spring WebClient is basically a reactive and non-blocking web client that can perform HTTP requests. It is aimed at providing a functional and fluent API style and was added to Spring 5.

2. What is the difference between WebClient and RestTemplate?

Before Spring 5, the RestTemplate had been the main technique used for client-side HTTP accesses. It is part of the Spring MVC project. But these days, WebClient is the most efficient approach. Before using the WebClient API, you should import the spring-boot-starter-webflux module into your project. You can do this easily:

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



That's all about how to use Spring 5 WebClient in Java. This is one of the most useful class for Java developer as we often need to integrate REST API in our application. If you are familiar with classes like WebClient and RestTemplate then you can confidently take any task which require fetching data from REST API or sending data to REST API.  

In this Spring 5 Web Client tutorial you have learned how to send GET and POST request, how to send request parameters and headers and also the difference between RestTemplate and WEbClient in Spring Framework. 

If you liked this list of 10 examples of Spring 5 WebClient in Java, feel free to share it with your friends and family.

Other Spring Framework Articles you may like

Thanks for reading this article so far. If you find these essential Spring WebClient examples then please share them with your friends and colleagues on Facebook and Twitter. If you have any questions or feedback then please drop a note.

P. S. - If you are new to Spring Framework and want to learn both Core Spring and Spring MVC from scratch then I highly recommend you join one of these Spring Framework online courses. It covers everything a Java developer needs to know about Spring Framework.


No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.