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
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.
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.