Prices change. To change a product that already exists, a client sends PUT to the product's own path, with the new version of the product in the JSON body. The server replaces the stored name, price and category with the ones it got. The id comes from the path, so it never changes.
A PUT route is written like the routes you know, with @PutMapping. Here is a small one that replaces a value in a map field settings (not part of the shop):
@PutMapping("/settings")
Map<String, Object> updateSettings(@RequestBody Map<String, Object> data) {
settings.put("theme", data.get("theme"));
return settings;
}
The shop holds many products, so your PUT first finds the one whose id is in the path, the same way getProduct does. It answers the changed product with 200 OK, or 404 when no product has that id. put only works on a map that can change: that's why the starting code now wraps each product in new HashMap<>(…). The requests and answers your code must give, in this order:
PUT /products/2 {"name": "Notebook", "price": 9, "category": "office"}
→ 200 {"id": 2, "name": "Notebook", "price": 9, "category": "office"}
GET /products/2 → 200 {"id": 2, "name": "Notebook", "price": 9, "category": "office"}
PUT /products/4 {"name": "Blue pen", "price": 3, "category": "office"}
→ 200 {"id": 4, "name": "Blue pen", "price": 3, "category": "office"}
PUT /products/99 {"name": "Cup", "price": 5, "category": "kitchen"}
→ 404 {"error": "Product not found"}
GET /products → 200 [{"id": 1, "name": "Mug", …}, {"id": 2, "name": "Notebook", "price": 9, …}, {"id": 3, "name": "Lamp", …}, {"id": 4, "name": "Blue pen", "price": 3, …}]
Your task: add PUT /products/{productId}. Its method updateProduct takes the id from the path and the JSON body as data, finds the product with that id, puts the name, price and category from data into it, and returns the changed product. When no product has that id, it answers 404 with {"error": "Product not found"}.
Assignment
Follow the Coding Tutorial to add the PUT route that replaces a product's name, price and category.
Hint
The annotation is the one of deleteProduct with Put in place of Delete, and the loop is the one from getProduct. Return the product inside the if, and the 404 after the loop. Java compiles the method only once both returns are there: a method that returns Object must return something on every path.
Free plan: 30 tutor messages. PRO is unlimited.
