Introduction
In this chapter, we will cover the @DeleteMapping annotation in Spring Boot. The @DeleteMapping annotation is used to handle HTTP DELETE requests, which are typically used for deleting existing resources. We will create endpoints to delete resources using this annotation, focusing on the Employee entity as our primary example.
Understanding @DeleteMapping Annotation
What is @DeleteMapping?
The @DeleteMapping annotation in Spring Boot is used to map HTTP DELETE requests to specific handler methods in a controller. It is a specialized version of the @RequestMapping annotation designed specifically for handling DELETE requests, which are used to remove resources from the server.
How @DeleteMapping Works
When a client sends an HTTP DELETE request to a specified URL, the @DeleteMapping annotation maps this request to a specific handler method in the controller. The method processes the request, typically deleting a resource from the server, and returns a response.
Key Features of @DeleteMapping
- Simplified Mapping:
@DeleteMappingprovides a clear and concise way to map HTTP DELETE requests to specific methods, making the code more readable and maintainable. - Handling Delete Operations: It is specifically designed for delete operations, making it easier to handle requests that remove existing resources.
- Path Variables and Query Parameters: Supports the use of
@PathVariableand@RequestParamannotations to extract values from the URL and query parameters, making the method flexible and dynamic.
Example Use Case
A common use case for @DeleteMapping is deleting a resource, such as removing an employee’s record from a database. The client specifies the resource to be deleted using a URL parameter, and the server processes the request and deletes the resource accordingly.
Setting Up the Project
We will continue using the project named springboot-crud-api that we created in the previous chapters.
Creating the Employee Entity
We already have the Employee entity created in the previous chapters. For reference, here is the Employee class:
package com.company.crudapi.model;
public class Employee {
private Long id;
private String firstName;
private String lastName;
private String email;
// Constructors
public Employee() {}
public Employee(Long id, String firstName, String lastName, String email) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Creating the REST Controller
Step 1: Update the EmployeeController Class
- Create or Update the Controller Class:
- In the
src/main/java/com/company/crudapi/controllerdirectory, open or create theEmployeeControllerclass. - Add the following code to the
EmployeeControllerclass:
- In the
package com.company.crudapi.controller;
import com.company.crudapi.model.Employee;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class EmployeeController {
private List<Employee> employees = new ArrayList<>(Arrays.asList(
new Employee(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com"),
new Employee(2L, "Suresh", "Kumar", "suresh.kumar@example.com"),
new Employee(3L, "Mahesh", "Yadav", "mahesh.yadav@example.com")
));
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employees;
}
@GetMapping("/employees/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employees.stream()
.filter(employee -> employee.getId().equals(id))
.findFirst()
.orElse(null);
}
@GetMapping("/employees/search")
public List<Employee> getEmployeesByLastName(@RequestParam String lastName) {
return employees.stream()
.filter(employee -> employee.getLastName().equalsIgnoreCase(lastName))
.collect(Collectors.toList());
}
@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee employee) {
employee.setId((long) (employees.size() + 1));
employees.add(employee);
return employee;
}
@PutMapping("/employees/{id}")
public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee updatedEmployee) {
return employees.stream()
.filter(employee -> employee.getId().equals(id))
.findFirst()
.map(employee -> {
employee.setFirstName(updatedEmployee.getFirstName());
employee.setLastName(updatedEmployee.getLastName());
employee.setEmail(updatedEmployee.getEmail());
return employee;
})
.orElse(null);
}
@DeleteMapping("/employees/{id}")
public String deleteEmployee(@PathVariable Long id) {
employees.removeIf(employee -> employee.getId().equals(id));
return "Employee deleted successfully!";
}
}
Explanation of DELETE REST API
1. DELETE Employee by ID
@DeleteMapping("/employees/{id}")
public String deleteEmployee(@PathVariable Long id) {
employees.removeIf(employee -> employee.getId().equals(id));
return "Employee deleted successfully!";
}
Explanation:
@DeleteMapping("/employees/{id}"): This annotation maps HTTP DELETE requests to the/employees/{id}URL to thedeleteEmployeemethod.@PathVariable Long id: This annotation binds the value of the{id}path variable to theidparameter in thedeleteEmployeemethod.- Method Logic: The method uses the
removeIfmethod to remove the employee with the matchingidfrom the list of employees. - Response: The method returns an “Employee deleted successfully!” success message to the client.
Running the Application
Step 2: Run Your Spring Boot Application
- Open Application Class:
- Ensure that the main application class (annotated with
@SpringBootApplication) is open.
- Ensure that the main application class (annotated with
- Run the Application:
- In IntelliJ IDEA, right-click the main application class and select “Run ‘SpringbootCrudApiApplication'”.
- Alternatively, open a terminal, navigate to the project directory, and run
mvn spring-boot:run.
Step 3: Test the DELETE API
- DELETE Employee by ID:
- Request:
DELETE http://localhost:8080/employees/1 - Response:

- Request:
Conclusion
In this chapter, we covered the @DeleteMapping annotation in Spring Boot, which is used to handle HTTP DELETE requests. We created an endpoint to delete an employee using this annotation and explained important attributes of the @DeleteMapping annotation. This completes our CRUD API implementation using Spring Boot.