Start learning free

LESSON 20 OF 173 · BACKEND: YOUR FIRST API

Add a Product in C#

Practice

Until now every route used GET, the method for reading. To send new data, a client uses POST. ASP.NET Core picks the function by the path and the method together, so app.MapGet("/products", …) and app.MapPost("/products", …) can go to two different functions.

A POST carries a request body, usually a JSON object. When the route's function takes a JsonElement data parameter, ASP.NET reads the body into it, and data.GetProperty("text").GetString() reads one key as text (GetInt32() reads a whole number). When something new is stored, the answer has the status 201 Created, written like the 404: the body, a comma, then statusCode: 201. Here is the idea on another route:

var messages = new List<string>();

app.MapPost("/messages", (JsonElement data) => {
    messages.Add(data.GetProperty("text").GetString());
    return Results.Json(new { count = messages.Count }, statusCode: 201);
});

The client doesn't choose the id: the shop gives the new product the largest id so far, plus 1, and adds it to products, so every route sees it. Your code must give, in this order:

POST /products  {"name": "Plant", "price": 15, "category": "home"}  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}
POST /products  {"name": "Stapler", "price": 9, "category": "office"}  →  201  {"id": 6, "name": "Stapler", "price": 9, "category": "office"}
GET /products/6  →  200  {"id": 6, "name": "Stapler", …}
GET /products?category=office  →  200  [{"id": 2, …}, {"id": 4, …}, {"id": 6, …}]
GET /products/count  →  200  {"count": 6}

Your task: add a POST /products route with app.MapPost whose function takes JsonElement data, gives the new product the next id, adds it to products and answers it with the status 201.


Assignment
Follow the Coding Tutorial to build the POST route for /products, from app.MapPost to the 201 answer.


Hint
Find the largest id with a variable that starts at 0 and a loop that keeps the biggest id it has seen; (int)product["id"] reads an id as a number. Build the new product in newProduct, not product, and return it with statusCode: 201.


STEP 1 OF 8
    Ctrl + Enter to check

    Shop Add Product in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free