Menu
CoddyTech

Reading a JSON Body

Part of the Minimal APIs section of Coddy's ASP.NET Core journey. Lesson 7 of 20.

A POST request sends data in its body, usually as JSON. When a POST lambda takes a record parameter, ASP.NET Core reads the body as JSON into it, matching names whatever their case.

app.MapPost("/notes", (NewNote input) =>
{
    var note = new Note(notes.Count + 1, input.Text);
    notes.Add(note);
    return Results.Created($"/notes/{note.Id}", note);
});

Results.Created answers 201 Created, the status for a new resource, with a Location header holding its address and the resource as the body. A value of the wrong type, like "text": 5, answers 400 before the lambda runs. A property the JSON leaves out gets its default: null or 0. On a laptop, curl sends a body with -d; here the request bar has a Body box.

challenge icon

Challenge

Easy

Clients can add recipes. They send everything but the id, and the API picks the next id.

  1. In Recipe.cs, add record NewRecipe(string Name, string Category, int Minutes);.
  2. In Program.cs, below the list, add var nextId = 4;.
  3. Map POST /api/recipes. Its lambda takes NewRecipe input, makes new Recipe(nextId++, input.Name, input.Category, input.Minutes) and adds it to recipes.
  4. Return Results.Created($"/api/recipes/{recipe.Id}", recipe).

Try it: press Run, pick POST, type the path /api/recipes and the body {"name":"Waffles","category":"breakfast","minutes":20}, then Send. The answer is status 201 with {"id":4,"name":"Waffles","category":"breakfast","minutes":20}, and the Headers tab shows Location: /api/recipes/4. Send GET /api/recipes/4: Waffles. Each Send replays your earlier POSTs on a fresh app, so the recipe is still there. Send the POST again: id 5.

Try it yourself

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var recipes = new List<Recipe>
{
    new(1, "Tomato Soup", "soup", 25),
    new(2, "Pancakes", "breakfast", 15),
    new(3, "Lentil Soup", "soup", 40),
};

app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", (string? category) =>
    recipes.Where(r => category is null || r.Category == category));
app.MapGet("/api/recipes/{id:int}", (int id) =>
{
    var recipe = recipes.FirstOrDefault(r => r.Id == id);
    if (recipe is null)
        return Results.NotFound(new { error = $"Recipe {id} not found" });
    return Results.Ok(recipe);
});

app.Run();
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Minimal APIs