Start learning free

LESSON 22 OF 188 · BACKEND: YOUR FIRST API

Remove a Product

Practice

To remove something, a client uses the DELETE method and names what to remove in the path. DELETE /products/2 has the same path as GET /products/2, but a different method, so Flask sends it to a different function.

A list's remove method takes out the item you give it. After a delete there is nothing to send back, so the answer is an empty body with the status 204 No Content. Here is the idea on another route:

tags = ["new", "sale", "gift"]

@app.delete("/tags/<name>")
def delete_tag(name):
    if name in tags:
        tags.remove(name)
        return "", 204
    return jsonify({"error": "Tag not found"}), 404

Your shop finds the product with a loop, like get_product, and answers 404 with the same error when no product has that id. Your code must give, in this order:

DELETE /products/2   →  204  (empty body)
GET /products/2      →  404  {"error": "Product not found"}
GET /products        →  200  [{"id": 1, …}, {"id": 3, …}, {"id": 4, …}]
DELETE /products/2   →  404  {"error": "Product not found"}
DELETE /products/99  →  404  {"error": "Product not found"}
GET /products/count  →  200  {"count": 3}
POST /products  {"name": "Plant", "price": 15, "category": "home"}  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}

Your task: add a DELETE /products/<int:product_id> route, delete_product, that removes the product with that id and answers 204 with an empty body, or 404 with {"error": "Product not found"} when there is no such product.


Assignment
Follow the Coding Tutorial to build delete_product.


Hint
Find the product with the same loop as in get_product. Return right after remove, inside the loop; the 404 goes after the loop, at the level of for.


STEP 1 OF 7
    Ctrl + Enter to check