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

Practice: A Book API in Memory

Your turn.

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

Let's practise everything from this module. Records, request parameters, streams, and Response Entity.

  • Records
  • Parameters and streams
  • ResponseEntity

Search by author

Your turn. Pause the video, and try this. Add GET slash books slash search, with an author parameter. Return the books whose author contains that text, ignoring case. If none match, return four oh four. Here is one solution. A stream filters the books, comparing in lower case. Herbert matches two books. Austen matches nothing, so we get four oh four.

✍️ Exercise: Search by author

GET /books/search?author=xx → 200 with the matching books (case-insensitive "contains"), or 404 if none match.

Show hint

books.stream().filter(...).toList(), then ok(...) or notFound().build()

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

    private final List<Book> books = List.of(
        new Book(1, "Dune", "Frank Herbert", 9.99),
        new Book(2, "Children of Dune", "Frank Herbert", 8.99),
        new Book(3, "Circe", "Madeline Miller", 10.99));

    @GetMapping("/search")
    public ResponseEntity<List<Book>> byAuthor(@RequestParam String author) {
        List<Book> found = books.stream()
            .filter(b -> b.author().toLowerCase().contains(author.toLowerCase()))
            .toList();
        return found.isEmpty() ? ResponseEntity.notFound().build()
                               : ResponseEntity.ok(found);
    }
}
Output
$ curl "localhost:8080/books/search?author=herbert"
[
  {"id":1,"title":"Dune","author":"Frank Herbert","price":9.99},
  {"id":2,"title":"Children of Dune","author":"Frank Herbert","price":8.99}
]
$ curl -i "localhost:8080/books/search?author=austen" | head -1
HTTP/1.1 404

What module three taught

REST uses noun URLs, and HTTP methods as verbs. Records hold our data, and Jackson turns them into JSON. At Request Body reads JSON from the client. And Response Entity sets the right status code.

keyvalue
RESTGET/POST/PUT/DELETE /books
Datarecords ↔ JSON
Input@RequestBody
OutputResponseEntity + status

Summary

You've built a complete REST API, in memory. That's the end of module three. Next module, how Spring connects the pieces, with beans, and dependency injection.

Key takeaways
  • A full REST API
  • Records and JSON
  • Proper status codes
Next up: Inversion of Control — who creates the objects?