Spring Boot WebClient POST Request Example

In this post, we’ll create a RESTful POST endpoint and demonstrate how to consume it using WebClient with a request body in the Spring Boot application.

Spring Boot WebClient POST Request Example

Our first task is to set up a simple Spring Boot application with a controller that will accept POST requests.

Step 1: Setting Up the Spring Boot Application 

Create a Spring Boot project using Spring Initializr with the following Maven dependency:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Step 2: Creating the REST Controller 

Let's define a BookController with a POST REST API that will accept a book object as the request body. 

BookController.java:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/books")
public class BookController {

    @PostMapping
    public ResponseEntity<Book> createBook(@RequestBody Book book) {
        // Simulate book creation
        book.setId(1L); // Mock ID assignment
        return new ResponseEntity<>(book, HttpStatus.CREATED);
    }

    // Nested class for a Book
    private static class Book {
        private Long id;
        private String title;
        private String author;

        // Constructors, getters, and setters
    }
}
In this example, the Book is a simple POJO with an id, title, and author. The controller simulates the creation of a book by setting an ID.

With our REST API ready to accept book data, let's turn our attention to WebClient and how it can be used to send POST requests with a request body. 

Step 3: Add WebClient Dependency 

To use WebClient, you need to add spring-boot-starter-webflux dependency:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

Step 4: Configure WebClient 

Create a configuration class to instantiate WebClient

WebClientConfig.java:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient() {
        return WebClient.builder()
                .baseUrl("http://localhost:8080/api/books")
                .build();
    }
}

Step 5: Creating REST Client for POST Request 

Now, we create a service class that uses WebClient to send a POST request with a Book object as the request body. 

BookServiceClient.java:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class BookServiceClient {

    private final WebClient webClient;

    @Autowired
    public BookServiceClient(WebClient webClient) {
        this.webClient = webClient;
    }

    public Mono<Book> createBook(Book book) {
        return webClient.post()
                        .bodyValue(book)
                        .retrieve()
                        .bodyToMono(Book.class);
    }
}
In the createBook method, we’re making a POST request where bodyValue(book) sets the request body. The retrieve() method processes the response, and bodyToMono(Book.class) converts it to a Mono<Book>.

Step 6: Using the Client Service 

To utilize the BookServiceClient, we’ll make a call from within our application to the REST API we created. 

DemoApplicationRunner.java:

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class DemoApplicationRunner implements CommandLineRunner {

    private final BookServiceClient bookServiceClient;

    public DemoApplicationRunner(BookServiceClient bookServiceClient) {
        this.bookServiceClient = bookServiceClient;
    }

    @Override
    public void run(String... args) {
        Book newBook = new Book("Spring in Action", "Craig Walls");

        bookServiceClient.createBook(newBook)
            .subscribe(book -> System.out.println("Created book: " + book.getTitle()));
    }
}
The CommandLineRunner will execute this code on startup, and the created book details will be outputted to the console. The subscribe() method initiates the POST request and processes the response reactively. 

Conclusion 

Spring Boot's WebClient is a versatile tool that simplifies HTTP client-side communication in a reactive way. With just a few configurations, you can make POST requests with complex objects as the request body, embracing the non-blocking nature of modern applications. 

Comments