A shop can't write a route for each of its products. Instead, one route has a placeholder in its path: a path parameter, written in angle brackets. In /products/<int:product_id>, the placeholder matches whatever is written in that place, so /products/3 matches with product_id equal to 3. Flask passes the value to your function, as a parameter with the same name.
The int: part is a converter: it matches only whole numbers, and turns them into an int. A path like /products/mug doesn't match, so it gets 404, and /products/count still goes to its own route. Here is the same idea on another route:
@app.get("/square/<int:number>")
def square(number):
return jsonify({"square": number * number})
Once you have the id, find the product with a loop: check each product's "id", and when it equals product_id, return that product. return ends the function, so the loop stops there.
Your app must answer:
GET /products/1 → 200 {"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}
GET /products/3 → 200 {"id": 3, "name": "Lamp", "price": 29, "category": "home"}
GET /products/4 → 200 {"id": 4, "name": "Pen", "price": 2, "category": "office"}
GET /products/count → 200 {"count": 4}
GET /products/mug → 404 (an HTML error page)
Your task: add a route for /products/<int:product_id> with a function named get_product that takes product_id, loops over products, and returns, as JSON, the product whose "id" equals product_id.
Assignment
Follow the Coding Tutorial to add the route that answers one product by its id.
Hint
The name inside the angle brackets and the parameter in the def line must be the same, product_id. Inside the loop, compare product["id"] with product_id.
Free plan: 30 tutor messages. PRO is unlimited.
