With PUT, a client sends the whole product, even to change one number: name, price and category, including the ones that stay the same. PATCH is the method for a partial change. Its body holds only the keys to change, like {"price": 5}, and every other key keeps its value.
So the route copies a key only when the body has it. A JsonElement's TryGetProperty tells you whether it has a key, and puts the key's value in an out variable when it does:
var data = JsonDocument.Parse("{\"price\": 5}").RootElement;
Console.WriteLine(data.TryGetProperty("price", out var price)); // True
Console.WriteLine(data.TryGetProperty("name", out var name)); // False
A client may change a product's name, price and category, but never its id: other requests find the product by it. So your route goes over a fixed list of those three keys and copies each one only if the body has it. An "id" in the body is never copied. The requests and answers your code must give, in this order:
PATCH /products/2 {"price": 5}
→ 200 {"id": 2, "name": "Notebook", "price": 5, "category": "office"}
GET /products/2 → 200 {"id": 2, "name": "Notebook", "price": 5, "category": "office"}
PATCH /products/3 {"name": "Desk lamp", "category": "office"}
→ 200 {"id": 3, "name": "Desk lamp", "price": 29, "category": "office"}
PATCH /products/1 {"id": 7, "price": 14}
→ 200 {"id": 1, "name": "Mug", "price": 14, "category": "kitchen"}
PATCH /products/4 {}
→ 200 {"id": 4, "name": "Pen", "price": 2, "category": "office"}
PATCH /products/99 {"price": 5}
→ 404 {"error": "Product not found"}
PUT /products/4 {"name": "Blue pen", "price": 3, "category": "office"}
→ 200 {"id": 4, "name": "Blue pen", "price": 3, "category": "office"}
GET /products → 200 [{"id": 1, "name": "Mug", "price": 14, …}, {"id": 2, "name": "Notebook", "price": 5, …}, {"id": 3, "name": "Desk lamp", …}, {"id": 4, "name": "Blue pen", …}]
Your task: add PATCH /products/{id:int}. It finds the product with that id, copies each of "name", "price" and "category" from the body only if the body has it, and answers the whole product. When no product has that id, it answers 404 with {"error": "Product not found"}.
Assignment
Follow the Coding Tutorial to add the PATCH route that changes only the keys the client sends.
Hint
The opening line, the loop and the if are the same as in the PUT route. Inside the if, loop over the three keys and copy one only when data.TryGetProperty(key, out var value) is true: the price with GetInt32(), the other two with GetString(). The return goes after the loop over the keys, still inside the if.
Free plan: 30 tutor messages. PRO is unlimited.
