The client sends POST slash books, with JSON in the body. A header says the body is JSON. Spring reads the body, and Jackson turns the JSON into a Book record. Our method receives the record, and saves it. And we send back the saved book, with its new id.
We keep books in a map, in memory, keyed by id. Next id counts up, from one. Get Mapping with no path, answers slash books itself. At Post Mapping handles POST. And at Request Body says, fill this book from the JSON body. We give it the next id, store it, and return it. With curl, dash dash json sends JSON, as a POST, with the right header. Run it. Dune gets id one, and Circe gets id two. Then GET lists both books.
BookController.javajava
@RestController@RequestMapping("/books")public class BookController { private final Map<Integer, Book> books = new LinkedHashMap<>(); private int nextId = 1; @GetMapping public Collection<Book> all() { return books.values(); } @PostMapping public Book add(@RequestBody Book book) { Book saved = new Book(nextId++, book.title(), book.author(), book.price()); books.put(saved.id(), saved); return saved; }}
What if the client sends something wrong? First, broken JSON. Second, form data instead of JSON. Run it. Broken JSON is a bad request, four hundred. And form data gets four one five, unsupported media type, because we only accept JSON.
BookController.javajava
@RestController@RequestMapping("/books")public class BookController { private final Map<Integer, Book> books = new LinkedHashMap<>(); private int nextId = 1; @GetMapping public Collection<Book> all() { return books.values(); } @PostMapping public Book add(@RequestBody Book book) { Book saved = new Book(nextId++, book.title(), book.author(), book.price()); books.put(saved.id(), saved); return saved; }}
Output
$ curl -i --json '{"title":"Dune", "price":}' localhost:8080/books | head -1
HTTP/1.1 400
$ curl -i -X POST -d 'title=Dune' localhost:8080/books | head -1
HTTP/1.1 415
Also uses Book.java
public record Book(Integer id, String title, String author, double price) {}
Also uses _curl.sh
curl -i --json '{"title":"Dune", "price":}' localhost:8080/books | head -1curl -i -X POST -d 'title=Dune' localhost:8080/books | head -1