Until now every route used GET, the method for reading. To send new data, a client uses POST. Spring picks the Java method to call by the path and the HTTP method together, so GET /products and POST /products can go to two different methods: one under @GetMapping, the other under @PostMapping.
A POST carries a request body, usually a JSON object. A parameter marked @RequestBody receives it, turned into a Java Map. When something new is stored, the answer has the status 201 Created, set the way you set the 404: ResponseEntity.status(201).body(…). Here is the idea on another route:
List<String> messages = new ArrayList<>();
@PostMapping("/messages")
Object addMessage(@RequestBody Map<String, Object> data) {
messages.add((String) data.get("text"));
return ResponseEntity.status(201).body(Map.of("count", messages.size()));
}
The client doesn't choose the id: the shop gives the new product the largest id so far, plus 1, and adds it to products, so every route sees it. Your code must give, in this order:
POST /products {"name": "Plant", "price": 15, "category": "home"} → 201 {"id": 5, "name": "Plant", "price": 15, "category": "home"}
POST /products {"name": "Stapler", "price": 9, "category": "office"} → 201 {"id": 6, "name": "Stapler", "price": 9, "category": "office"}
GET /products/6 → 200 {"id": 6, "name": "Stapler", …}
GET /products?category=office → 200 [{"id": 2, …}, {"id": 4, …}, {"id": 6, …}]
GET /products/count → 200 {"count": 6}
Your task: add a POST /products method, addProduct, that takes the JSON body as data, gives the new product the next id, adds it to products and answers it with the status 201.
Assignment
Follow the Coding Tutorial to build addProduct, from the @PostMapping to the 201 answer.
Hint
Find the largest id with an int that starts at 0 and a loop that keeps the biggest id it has seen. Build the new product with Map.of in newProduct and return it with ResponseEntity.status(201). Until that return is written, javac reports missing return statement, so the app only starts after the last step.
Free plan: 30 tutor messages. PRO is unlimited.
