Menu
CoddyTech

JSONボディを読む

CoddyのASP.NET Coreジャーニー「Minimal API」セクションの一部。レッスン 7/20。

POSTリクエストは本文でデータを送信し、通常はJSONとして送ります。POSTのラムダがレコード型のパラメーターを受け取ると、ASP.NET Coreは本文をJSONとして読み込んでそのパラメーターに格納し、名前の大文字と小文字は区別しません。

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は、新しいリソースを示すステータスコード201 Createdを返します。アドレスを格納したLocationヘッダーと、本文としてリソースを返します。"text": 5のように型が間違っている値があると、ラムダが実行される前に400を返します。JSONに含まれていないプロパティには、nullまたは0という既定値が設定されます。ノートパソコンでは、curlで-dを使って本文を送信します。ここでは、リクエストバーにBodyボックスがあります。

challenge icon

チャレンジ

簡単

クライアントはレシピを追加できます。id以外のすべてを送信し、APIが次のidを割り当てます。

  1. Recipe.csで、record NewRecipe(string Name, string Category, int Minutes);を追加します。
  2. Program.csで、リストの下にvar nextId = 4;を追加します。
  3. POST /api/recipesをマッピングします。ラムダはNewRecipe inputを受け取り、new Recipe(nextId++, input.Name, input.Category, input.Minutes)を作成して、recipesに追加します。
  4. Results.Created($"/api/recipes/{recipe.Id}", recipe)を返します。

試してみましょう:「実行」を押し、POSTを選択して、パスに/api/recipes、本文に{"name":"Waffles","category":"breakfast","minutes":20}を入力し、「送信」を押します。ステータス201と{"id":4,"name":"Waffles","category":"breakfast","minutes":20}が返り、「Headers」タブにはLocation: /api/recipes/4と表示されます。GET /api/recipes/4を送信すると、Wafflesが返ります。「送信」のたびに、新しいアプリで以前のPOSTが再実行されるため、レシピはそのまま残っています。POSTをもう一度送信すると、idは5になります。

自分で試してみよう

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 icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Minimal APIのすべてのレッスン