7.1.4 Deleting data from the server
Sometimes data simply isn’t needed anymore. In those cases, a client should be able to request that a resource be removed with an HTTP DELETE request.
Spring MVC’s @DeleteMapping comes in handy for declaring methods that handle DELETE requests. For example, let’s say you want your API to allow for an order resource to be deleted. The following controller method should do the trick:
@DeleteMapping("/{orderId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteOrder(@PathVariable("orderId") Long orderId) {
try {
repo.deleteById(orderId);
} catch (EmptyResultDataAccessException e) {}
}By this point, the idea of another mapping annotation should be old hat to you. You’ve already seen @GetMapping, @PostMapping, @PutMapping, and @PatchMapping — each specifying that a method should handle requests for their corresponding HTTP methods. It will probably come as no surprise to you that @DeleteMapping is used to specify that the deleteOrder() method is responsible for handling DELETE requests for /orders/{orderId}.
The code within the method is what does the actual work of deleting an order. In this case, it takes the order ID, provided as a path variable in the URL, and passes it to the repository’s deleteById() method. If the order exists when that method is called, it will be deleted. If the order doesn’t exist, an EmptyResultDataAccessException will be thrown.
I’ve chosen to catch the EmptyResultDataAccessException and do nothing with it. My thinking here is that if you try to delete a resource that doesn’t exist, the outcome is the same as if it did exist prior to deletion—that is, the resource will be nonexistent. Whether it existed before is irrelevant. Alternatively, I could’ve written deleteOrder() to return a ResponseEntity, setting the body to null and the HTTP status code to NOT FOUND.
The only other thing to take note of in the deleteOrder() method is that it’s annotated with @ResponseStatus to ensure that the response’s HTTP status is 204 (NO CONTENT). There’s no need to communicate any resource data back to the client for a resource that no longer exists, so responses to DELETE requests typically have no body and, therefore, should communicate an HTTP status code to let the client know not to expect any content.
Your Taco Cloud API is starting to take shape. Now a client can be written to consume this API, presenting ingredients, accepting orders, and displaying recently created tacos. We’ll talk about writing REST client code a little later in 7.3. But for now, let’s see another way to create REST API endpoints: automatically based on Spring Data repositories.
