Spring Boot DELETE REST API – @DeleteMapping Annotation

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

  1. Simplified Mapping: @DeleteMapping provides a clear and concise way to map HTTP DELETE requests to specific methods, making the code more readable and maintainable.
  2. Handling Delete Operations: It is specifically designed for delete operations, making it easier to handle requests that remove existing resources.
  3. Path Variables and Query Parameters: Supports the use of @PathVariable and @RequestParam annotations 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

  1. Create or Update the Controller Class:
    • In the src/main/java/com/company/crudapi/controller directory, open or create the EmployeeController class.
    • Add the following code to the EmployeeController class:
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 the deleteEmployee method.
  • @PathVariable Long id: This annotation binds the value of the {id} path variable to the id parameter in the deleteEmployee method.
  • Method Logic: The method uses the removeIf method to remove the employee with the matching id from 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

  1. Open Application Class:
    • Ensure that the main application class (annotated with @SpringBootApplication) is open.
  2. 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: Spring Boot DELETE REST API - @DeleteMapping Annotation

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.

Leave a Comment

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

Scroll to Top