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

ResponseEntity

Full control of the response.

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

Until now, Spring always answered two hundred. But a missing book should be four oh four. Response Entity lets us choose the status, the headers, and the body.

  • Always 200 so far
  • Missing should be 404
  • Choose everything

ResponseEntity builders

Response Entity is the whole HTTP response, as one Java object. Response Entity dot ok, gives two hundred, with a body. Not found, then build, gives four oh four, with no body. And status lets you pick any code you like.

keyvalue
ResponseEntity<Book>status + headers + body
ResponseEntity.ok(book)200 with a body
notFound().build()404, no body
status(418).body(x)any status

Found or not found

The method now returns Response Entity of Book. If the book is missing, we return not found. Otherwise, we return ok, with the book as the body. Run it. Book one comes back with two hundred, and the JSON. Book nine gives a clean four oh four, with no body at all.

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)));

    @GetMapping("/{id}")
    public ResponseEntity<Book> one(@PathVariable int id) {
        Book book = books.get(id);
        if (book == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(book);
    }
}
Output
$ curl -i localhost:8080/books/1
HTTP/1.1 200
Content-Type: application/json

{"id":1,"title":"Dune","author":"Frank Herbert","price":9.99}
$ curl -i localhost:8080/books/9
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 localhost:8080/books/1
curl -i localhost:8080/books/9

Summary

Response Entity controls the status, headers, and body. Use ok for success, and not found for missing things. Next, status codes in practice.

Key takeaways
  • ResponseEntity<Book>
  • ok(book)
  • notFound().build()
Next up: Status Codes in Practice — 201, 204, 404