Menu
CoddyTech

PUTによる更新

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

PUTリクエストは、送信する本文で指定したアドレスのリソースを置き換えます。そのラムダは、ルートパラメーターと本文をまとめて受け取ります。

app.MapPut("/notes/{id:int}", (int id, NewNote input) =>
{
    var index = notes.FindIndex(n => n.Id == id);
    if (index == -1)
        return Results.NotFound();
    notes[index] = new Note(id, input.Text);
    return Results.Ok(notes[index]);
});

FindIndexは最初に一致した項目の位置を返し、一致する項目がない場合は-1を返します。レコードは作成後に変更できないため、エンドポイントは同じidを持つ新しいレコードを作成し、その位置に配置します。同じPUTを2回送信しても結果は同じですが、同じPOSTを2回送信するとリソースが2つ追加されます。

challenge icon

チャレンジ

簡単

クライアントはレシピを変更できます。

  1. Program.csでPUT /api/recipes/{id:int}をマッピングします。そのラムダはint idとNewRecipe inputを受け取ります。
  2. recipes.FindIndex(r => r.Id == id)でレシピの位置を見つけます。-1の場合は、Results.NotFound(new { error = $"Recipe {id} not found" })を返します。
  3. そうでなければ、new Recipe(id, input.Name, input.Category, input.Minutes)を作成し、recipesのその位置に入れて、Results.Ok(recipe)を返します。

試してみましょう:「実行」を押し、PUTを選択して、パスに/api/recipes/2、本文に{"name":"Banana Pancakes","category":"breakfast","minutes":20}を入力し、「送信」します。ステータス200と{"id":2,"name":"Banana Pancakes","category":"breakfast","minutes":20}が返ります。GET /api/recipesを送信します。レシピは3つで、真ん中にBanana Pancakesがあります。/api/recipes/99へのPUTには404が返ります。

自分で試してみよう

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),
};
var nextId = 4;

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.MapPost("/api/recipes", (NewRecipe input) =>
{
    if (string.IsNullOrWhiteSpace(input.Name))
        return Results.BadRequest(new { error = "Name is required" });
    if (input.Minutes <= 0)
        return Results.BadRequest(new { error = "Minutes must be more than 0" });
    var recipe = new Recipe(nextId++, input.Name, input.Category, input.Minutes);
    recipes.Add(recipe);
    return Results.Created($"/api/recipes/{recipe.Id}", recipe);
});

app.Run();

Minimal APIのすべてのレッスン