An AI assistant wrote the product page for this shop. Its get_product asks the database for one product and answers its name, its price and whether it is in stock. Here is the AI's version:
@app.get("/products/<int:product_id>")
def get_product(product_id):
row = db.execute("SELECT * FROM products WHERE id = ?", (product_id,)).fetchone()
return jsonify({"name": row["name"], "price": row["price"], "in_stock": row["stock"] > 0})
It works for every product that exists. But when no product has the id, fetchone() gives None, and row["name"] crashes with a TypeError. Flask answers 500 Internal Server Error with an HTML page. The AI wrote the happy path and forgot the missing case.
The fix is a check that runs before the code uses the value. Here it is on another route, for coupons kept in a dictionary:
@app.get("/coupons/<coupon_code>")
def get_coupon(coupon_code):
coupon = COUPONS.get(coupon_code)
if coupon is None:
return jsonify({"error": "Coupon not found"}), 404
return jsonify(coupon)
A 404 says "there is no such thing", in JSON the client can read. Your code must give these answers:
GET /products/1 → 200 {"name": "Mug", "price": 12, "in_stock": true}
GET /products/2 → 200 {"name": "Notebook", "price": 7, "in_stock": false}
GET /products/8 → 200 {"name": "Gift card", "price": 50, "in_stock": true}
GET /products/99 → 404 {"error": "Product not found"}
GET /products/0 → 404 {"error": "Product not found"}
Your task: rewrite get_product. Ask the database for the product with this id. If there is no row, answer {"error": "Product not found"} with 404; otherwise answer its name, its price and in_stock (true when the stock is above 0).
Assignment
Follow the Coding Tutorial to rewrite get_product with the missing case handled.
Hintfetchone() gives None when no row matches. Check row is None before any line reads row["..."], and put , 404 after the error body.
Free plan: 30 tutor messages. PRO is unlimited.
