Start learning free

LESSON 24 OF 188 · BACKEND: YOUR FIRST API

Change Only the Price (PATCH) in Python

Practice

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. Python's in tells you whether a dictionary has a key:

data = {"price": 5}
print("price" in data)   # True
print("name" in data)    # 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/<int:product_id>. 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 first lines are the same as in update_product. Inside the if, loop over the three keys and check key in data before copying. Watch the indentation: the return goes after the loop over the keys, still inside the if.


STEP 1 OF 10
    Ctrl + Enter to check

    Shop Patch Price in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free