Start learning free

LESSON 23 OF 188 · BACKEND: YOUR FIRST API

Update a Product (PUT)

Practice

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.put. Here is a small one that replaces a value in a dictionary settings (not part of the shop):

@app.put("/settings")
def update_settings():
    data = request.get_json()
    settings["theme"] = data["theme"]
    return jsonify(settings)

The shop holds many products, so your PUT first finds the one whose id is in the path, the same way get_product 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/<int:product_id>. It reads the JSON body, finds the product with that id, sets its name, price and category to the values in the body, 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 decorator is the one of delete_product with put in place of delete, and the loop is the one from get_product. Return the product inside the if, and the 404 after the loop, so the 404 only runs when no product matched.


STEP 1 OF 10
    Ctrl + Enter to check