Start learning free

LESSON 22 OF 173 · 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 ASP.NET Core sends it to a different function, one you map with app.MapDelete.

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: Results.StatusCode(204). Here is the idea on another route:

var tags = new List<string> { "new", "sale", "gift" };

app.MapDelete("/tags/{name}", (string name) => {
    if (tags.Contains(name)) {
        tags.Remove(name);
        return Results.StatusCode(204);
    }
    return Results.Json(new { error = "Tag not found" }, statusCode: 404);
});

Your shop finds the product with a foreach loop, like the GET route for one product, and answers 404 with the same error when no product has that id. Return right after Remove: a foreach must not go on over a list that just changed. 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/{id:int} route with app.MapDelete 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 the DELETE route for /products/{id:int}.


Hint
Find the product with the same loop as the GET route for one product. Return right after Remove, inside the if; the 404 goes after the loop, at the level of foreach. C# won't compile the route until every path returns something.


STEP 1 OF 6
    Ctrl + Enter to check