x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Spring Boot WebClient example

    Spring Boot provides WebClient to call REST APIs which was added in Spring 5 in reactive style unlike RestTemplate. Also unlike RestTemplate, WebClient doesn't expose multiple methods for various types of calls. Instead WebClient provides builder which can be used to create various types of requests. Typical steps are to create a WebClient instance, specify HTTP method, URI, headers, submit the request and process response.

    In this example, we will use fake API server where we will send requests using WebClient. GET request will retrieve the product details for a product, POST request will be used to create a new Product, and DELTE will delete the product.

    Below are the steps to create and run the Sprint Boot application with WebClient:

    Step 1) Create pom.xml

    In the pom.xml add spring-boot-starter-webflux dependency

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

    Step 2) Create Product POJO class which contains product details

    package com.example.demo;
    
    public class Product {
    
        private int id;
    	private String title;
    	private float price;
    	private String description;
    	private String clothing;
        
        // removed constructor, getter and setter for brevity
    
    }       

    Step 3) Create WebConfig class which contains configuration for WebClient.

    package com.example.demo;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.reactive.function.client.WebClient;
    
    @Configuration
    public class WebConfig {
    
        @Bean
        public WebClient webClient() {
                WebClient webClient 
                    = WebClient.builder().baseUrl("https://fakestoreapi.com/").build();
                return webClient;
        }
    }   

    Step 4) Create ProductClientController class

    ProductClientController class will expose REST enpoints to invoke WebClient, which in turn will call APIs to get, create, delete product. The retrieve() method will execute the request while bodyToMono() call will extract the response’s body payload into a Mono<Product>.

    Spring WebClient handling errors

    You can also handle error in case WebClient call fails. For example if service throws 400 or 500 error code series, you can process the Exception using WebClient onStatus method and HttpStatus is4xxClientError & is5xxClientError methods.

    package com.example.demo;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.reactive.function.client.WebClient;
    
    import reactor.core.publisher.Mono;
    
    @RestController
    @RequestMapping("/products")
    public class ProductClientController {
    
    private final WebClient webClient;
    
        @Autowired
        public ProductClientController(WebClient webClient) {
            this.webClient = webClient;
        }
    
        @GetMapping("/{id}")
        public Mono<Product> getProduct(@PathVariable("id") String id) {
            Mono<Product> product = webClient
                .get()
                .uri("/products/{id}", id)
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, response 
                    -> Mono.just(new RuntimeException("data not found")))
                .bodyToMono(Product.class);
            return product;
        }
    
        @PostMapping("/")
        public Mono<Product> addProduct(@RequestBody Product product) {
            Mono<Product> newProduct = webClient.post().uri("/products/")
                        .bodyValue(product).retrieve().bodyToMono(Product.class);
            newProduct.subscribe(System.out::println);
            return newProduct;
        }
        
        @DeleteMapping("/{id}")
    	public Mono<Product> deleteProduct(@PathVariable("id") String id) {
    		Mono<Product> deletedProduct = webClient.delete().uri("/products/{id}",
                id).retrieve().bodyToMono(Product.class);
    		deletedProduct.subscribe(System.out::println);
    		return deletedProduct;
    	}
    
    }      

    Step 5) Create ProductClientApplication class

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class ProductClientApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(UserApplication.class, args);
        }
            
    }       

    Step 6) Testing WebClient

    Open any browser and launch http://localhost:8080/products/1. You will see product details for product id 1 displayed in the broswer.


    WebClient GET










    If you want to add a product, then you need to send a POST request as below

    WebClient POST
















    If you want to delete a product, then you need to send a DELETE request as below

    WebClient DELETE
















    References :

    Spring Boot WebClient

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This