@DeleteMapping in Spring: What It Is and How to Use It
@DeleteMapping is a Spring annotation used to map HTTP DELETE requests to specific handler methods in a controller. It helps define endpoints that delete resources on the server, making REST APIs clear and organized.How It Works
@DeleteMapping is like a signpost in your Spring controller that tells the app: "When someone sends a DELETE request to this URL, run this method." Imagine you have a list of items, and you want to remove one. The DELETE request is the action to remove, and @DeleteMapping connects that action to the code that does the removal.
Under the hood, Spring listens for HTTP DELETE requests at the URL you specify in @DeleteMapping. When it sees one, it calls the method annotated with it. This method can then delete data from a database or perform other cleanup tasks.
Example
This example shows a simple Spring controller method that deletes a user by their ID when a DELETE request is sent to /users/{id}.
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @DeleteMapping("/users/{id}") public String deleteUser(@PathVariable String id) { // Imagine code here that deletes the user from a database return "User with ID " + id + " deleted successfully."; } }
When to Use
Use @DeleteMapping when you want to create REST API endpoints that remove or delete resources, such as users, files, or records. It clearly signals that the endpoint is for deletion, making your API easier to understand and maintain.
For example, if you build an app where users can delete their accounts or remove items from a list, @DeleteMapping is the right choice to handle those requests.
Key Points
@DeleteMappingmaps HTTP DELETE requests to controller methods.- It is part of Spring's REST support to build clear and semantic APIs.
- Use it to handle resource deletion actions in your web app.
- Works with path variables to specify which resource to delete.
Key Takeaways
@DeleteMapping handles HTTP DELETE requests in Spring controllers.@DeleteMapping makes REST APIs clear and easy to understand.