Spring Boot WebClient DELETE Request Example

In this tutorial, we will build a 'Delete Employee' REST API with MySQL database and then we will demonstrate how to consume it using WebClient.

1. Building a 'Delete Employee' REST API in Spring Boot

First, you'll set up a Spring Boot application with a MySQL database to store and delete employee data. Then, you'll create a service to handle data persistence and finally use WebClient to delete an employee's data. Let's get started.

Step 1: Set Up the Spring Boot Project with MySQL 

Add the necessary dependencies to your pom.xml:

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

<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <optional>true</optional>
</dependency>

Step 2: Configure MySQL Database 

Set up your application.properties or application.yml with your MySQL configuration: 

application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Replace your_databaseyour_username, and your_password with your actual MySQL database name and credentials.

Step 3: Create the Employee Entity and Repository 

Define an Employee entity and a corresponding repository. 

Employee.java:
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String department;
    
    // Constructors, getters, and setters can be omitted for brevity (use Lombok)
}
EmployeeRepository.java:
import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    // Custom methods if needed
}

Step 4: Implement the Service Layer 

Create a service to handle CRUD operations. 

EmployeeService.java:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {

    private final EmployeeRepository employeeRepository;

    @Autowired
    public EmployeeService(EmployeeRepository employeeRepository) {
        this.employeeRepository = employeeRepository;
    }

    public void deleteEmployee(Long id) {
        employeeRepository.deleteById(id);
    }
}

Step 5: Create the REST Controller 

Create the REST controller that exposes the DELETE operation:

EmployeeController.java:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    private final EmployeeService employeeService;

    @Autowired
    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteEmployee(@PathVariable Long id) {
        employeeService.deleteEmployee(id);
        return ResponseEntity.noContent().build();
    }
}

2. Consuming the API with WebClient 

With the server side ready, let's demonstrate how to consume the 'Delete Employee' REST API using WebClient. 

Step 1: Configure WebClient

Set up WebClient in your configuration:
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/employees")
                .build();
    }
}

Step 2: Implement WebClient Service

Implement WebClient Service Create a service that uses WebClient to send a DELETE request:

WebClientService.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 WebClientService {

    private final WebClient webClient;

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

    public Mono<Void> deleteEmployee(Long id) {
        return webClient.delete()
                        .uri("/{id}", id)
                        .retrieve()
                        .bodyToMono(Void.class);
    }
}

In the deleteEmployee method, the URI is constructed with the employee ID as a path variable, and the response is converted to a Mono<Void> indicating the completion of the operation.

Step 3: Use WebClient Service in the Application

Finally, you can use the WebClientService from any part of your application to trigger the delete operation:

ApplicationRunner.java:
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class ApplicationRunner implements CommandLineRunner {

    private final WebClientService webClientService;

    public ApplicationRunner(WebClientService webClientService) {
        this.webClientService = webClientService;
    }

    @Override
    public void run(String... args) {
        webClientService.deleteEmployee(1L)
            .subscribe(
                null,
                error -> System.err.println("Error during deletion: " + error),
                () -> System.out.println("Deletion completed!")
            );
    }
}
The CommandLineRunner here makes a non-blocking call to delete the employee with ID 1. The subscribe method is called without a data consumer because we do not expect a response body for a DELETE operation. 

Conclusion 

In this post, we've built a comprehensive Spring Boot application that connects to a MySQL database and exposes a DELETE endpoint for removing employee records. We've also seen how WebClient can be used to consume this endpoint, illustrating the power and simplicity of Spring Boot when it comes to building and interacting with RESTful services. Remember to secure your endpoints appropriately in production and manage your database connections for optimal performance.

Comments