AI Hints
Home›Spring Boot Tutorial›ResponseEntity, Status Codes in Practice and Practice: A Book API in Memory
Spring Boot · Lesson 26 of 120

Status Codes in Practice

201, 204, 404.

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

A good API uses the right status code for each answer. Clients rely on them, to know what happened.

  • The right code
  • For each answer
  • Clients rely on it

Which code when?

A successful GET, or PUT, returns two hundred. A POST that creates something returns two oh one, created. It also sends a Location header, with the URL of the new thing. A successful DELETE returns two oh four, no content. And anything missing returns four oh four.

ActionSuccessMissing
GET /books/1200 OK404
POST /books201 Created + Location—
PUT /books/1200 OK404
DELETE /books/1204 No Content404

201 and 204

Add now returns created, with the location of the new book, and the book as the body. Remove returns Response Entity of Void, which means no body. If nothing was removed, it's four oh four. Otherwise, it's no content. Run it. The POST gives two oh one, with a location of slash books slash one. The first delete gives two oh four. And deleting again gives four oh four.

BookController.javajava
@RestController
public class BookController {

    private final Map<Integer, Book> books = new HashMap<>();
    private int nextId = 1;

    @PostMapping("/books")
    public ResponseEntity<Book> add(@RequestBody Book book) {
        Book saved = new Book(nextId++, book.title(), book.author(), book.price());
        books.put(saved.id(), saved);
        return ResponseEntity.created(URI.create("/books/" + saved.id())).body(saved);
    }

    @DeleteMapping("/books/{id}")
    public ResponseEntity<Void> remove(@PathVariable int id) {
        return books.remove(id) == null ? ResponseEntity.notFound().build()
                                        : ResponseEntity.noContent().build();
    }
}
Output
$ curl -i --json '{"title":"Dune","author":"Herbert","price":9.99}' localhost:8080/books
HTTP/1.1 201
Location: /books/1
Content-Type: application/json

{"id":1,"title":"Dune","author":"Herbert","price":9.99}
$ curl -i -X DELETE localhost:8080/books/1
HTTP/1.1 204
$ curl -i -X DELETE localhost:8080/books/1
HTTP/1.1 404
Also uses Book.java
public record Book(Integer id, String title, String author, double price) {}
Also uses _curl.sh
curl -i --json '{"title":"Dune","author":"Herbert","price":9.99}' localhost:8080/books
curl -i -X DELETE localhost:8080/books/1
curl -i -X DELETE localhost:8080/books/1

Summary

POST returns two oh one, with a Location header. DELETE returns two oh four. And missing things return four oh four. Next, some practice.

Key takeaways
  • 201 Created + Location
  • 204 No Content
  • 404 Not Found
Next up: Practice: A Book API in Memory — your turn