AI Hints
Home›Spring Boot Tutorial›@PostMapping and @RequestBody, @PutMapping and @DeleteMapping
Spring Boot · Lesson 24 of 120

@DeleteMapping

Removing data.

⏱ 2 min read▶ Video at 31:56🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

The last of the four main methods is DELETE. It removes one thing, named by its URL.

  • The last verb
  • Remove one thing
  • Named by its URL

Deleting a book

The map starts with two books. At Delete Mapping handles DELETE, on slash books slash id. Map remove returns the removed book, or null if there was none. Run it. The first delete removes Dune. The second finds nothing to delete. And now only Circe is left.

BookController.javajava
@RestController
@RequestMapping("/books")
public class BookController {

    private final Map<Integer, Book> books = new LinkedHashMap<>(Map.of(
        1, new Book(1, "Dune", "Frank Herbert", 9.99),
        2, new Book(2, "Circe", "Madeline Miller", 10.99)));

    @GetMapping
    public Collection<Book> all() {
        return books.values();
    }

    @DeleteMapping("/{id}")
    public String remove(@PathVariable int id) {
        Book gone = books.remove(id);
        return gone == null ? "Nothing to delete" : "Deleted " + gone.title();
    }
}
Output
$ curl -X DELETE localhost:8080/books/1
Deleted Dune
$ curl -X DELETE localhost:8080/books/1
Nothing to delete
$ curl localhost:8080/books
[{"id":2,"title":"Circe","author":"Madeline Miller","price":10.99}]
Also uses Book.java
public record Book(Integer id, String title, String author, double price) {}
Also uses _curl.sh
curl -X DELETE localhost:8080/books/1
curl -X DELETE localhost:8080/books/1
curl localhost:8080/books

Our full API so far

Together, these give a full API, often called CRUD. Create with POST, read with GET, update with PUT, and delete with DELETE. Almost every API in the world is built from these four.

CRUDMethodAnnotation
CreatePOST@PostMapping
ReadGET@GetMapping
UpdatePUT@PutMapping
DeleteDELETE@DeleteMapping

One problem left

Look at the responses. A missing book returned two hundred, with a message, or even an empty body. That's wrong. Missing things should return four oh four. Next, we'll fix that, with Response Entity.

keyvalue
Now200 for everything
Missing bookshould be 404
New bookshould be 201
FixResponseEntity

Summary

At Delete Mapping removes a thing. With POST, GET, PUT, and DELETE, we have a full CRUD API. Next, Response Entity, for proper status codes.

Key takeaways
  • @DeleteMapping
  • CRUD
  • Status codes next
Next up: ResponseEntity — full control of the response