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 app.MapPut. Here is a small one that replaces a value in a dictionary settings (not part of the shop):
app.MapPut("/settings", (JsonElement data) => {
settings["theme"] = data.GetProperty("theme").GetString();
return Results.Json(settings);
});
The shop holds many products, so your PUT first finds the one whose id is in the path, the same way the GET /products/{id:int} route does. It answers the changed product with 200 OK, or 404 when no product has that id. 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/{id:int}. Its function takes int id and JsonElement data, finds the product with that id, sets its name, price and category to the values in the body (the price read with GetInt32()), and answers 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 opening line is the DELETE route's, with MapPut and a second parameter JsonElement data, and the loop is the one from the GET route for one product. Return the product inside the if and the 404 after the loop. C# wants a return on every path, so the route compiles only once the 404 line is there.
Free plan: 30 tutor messages. PRO is unlimited.
