To remove something, a client uses the DELETE method and names what to remove in the path. DELETE /products/2 has the same path as GET /products/2, but a different HTTP method, so Spring sends it to a different Java method: the one under @DeleteMapping.
A list's remove method takes out the item you give it. After a delete there is nothing to send back, so the answer has no body and the status 204 No Content: ResponseEntity.noContent().build(). Here is the idea on another route:
List<String> tags = new ArrayList<>(List.of("new", "sale", "gift"));
@DeleteMapping("/tags/{name}")
Object deleteTag(@PathVariable String name) {
if (tags.contains(name)) {
tags.remove(name);
return ResponseEntity.noContent().build();
}
return ResponseEntity.status(404).body(Map.of("error", "Tag not found"));
}
Your shop finds the product with a loop, like getProduct, and answers 404 with the same error when no product has that id. Your code must give, in this order:
DELETE /products/2 → 204 (empty body)
GET /products/2 → 404 {"error": "Product not found"}
GET /products → 200 [{"id": 1, …}, {"id": 3, …}, {"id": 4, …}]
DELETE /products/2 → 404 {"error": "Product not found"}
DELETE /products/99 → 404 {"error": "Product not found"}
GET /products/count → 200 {"count": 3}
POST /products {"name": "Plant", "price": 15, "category": "home"} → 201 {"id": 5, "name": "Plant", "price": 15, "category": "home"}
Your task: add a @DeleteMapping("/products/{productId}") method, deleteProduct, that removes the product with that id and answers 204 with no body, or 404 with {"error": "Product not found"} when there is no such product.
Assignment
Follow the Coding Tutorial to build deleteProduct.
Hint
Find the product with the same loop as in getProduct. Return right after remove, inside the if; the 404 goes after the loop. Until it is there, javac reports missing return statement, because the method could end without an answer.
Free plan: 30 tutor messages. PRO is unlimited.
