When no product has the id that was asked for, the loop in get_product ends without returning anything. A Python function that ends without return gives back None, and Flask can't send that, so it answers 500 Internal Server Error: the server's fault. But nothing broke: the product just isn't there.
The status code tells the client how its request went: 200 means OK, 404 means Not Found, 500 means the server failed. A plain return sends 200. To send another status, return two values separated by a comma: the body, then the status. For example, a members-only page could answer 403, which means Forbidden:
@app.get("/vip")
def vip():
return jsonify({"error": "Members only"}), 403
An API answers its errors in JSON too, like {"error": "Product not found"}, so the client's program can read what went wrong. The error belongs after the loop: those lines run only when no product matched.
Your app must answer:
GET /products/99 → 404 {"error": "Product not found"}
GET /products/2 → 200 {"id": 2, "name": "Notebook", "price": 7, "category": "office"}
GET /products/0 → 404 {"error": "Product not found"}
GET /products/5 → 404 {"error": "Product not found"}
GET /products/lamp → 404 (an HTML error page)
Your task: after the loop in get_product, make a dictionary named error with the key "error" and the value "Product not found", and return it as JSON with the status 404.
Assignment
Follow the Coding Tutorial to answer 404 with a JSON error when no product has the requested id.
Hint
The two new lines go after the loop, indented like the for line, not inside it. The status comes after the body, separated by a comma.
Free plan: 30 tutor messages. PRO is unlimited.
