Menu
CoddyTech

PUTによる置き換え

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

PUTは項目を置き換えます。本文は項目の新しい状態全体で、項目自身のURLに送信されます。本文に含まれていないフィールドには既定値が設定されます。同じPUTを2回送信しても結果は同じなので、PUTは冪等です。タイムアウト後にクライアントが再試行してもかまいません。2回目のPOSTでは別の項目が追加されるため、POSTは冪等ではありません。

app.MapPut("/api/products/{id:int}", (int id, ProductInput input) =>
{
    var index = products.FindIndex(p => p.Id == id);
    if (index == -1) return Results.NotFound();
    products[index] = new Product(id, input.Name, input.Price);
    return Results.Ok(products[index]);
});

idは本文ではなくパスから取得するため、クライアントが商品を別のidに移すことはできません。FindIndexはリスト内の項目の位置を返します。一致するものがない場合は-1を返します。また、products[index] = ...は新しいバージョンをその位置に保存します。

challenge icon

チャレンジ

簡単

クライアントがタスクを置き換えられるようにします。

  1. Program.csで、int idとTaskInput inputパラメーターを使ってPUT /api/tasks/{id:int}をマップします。本文の形式はPOSTの本文と同じです。
  2. tasks.FindIndexでタスクの位置を見つけます。値が-1の場合はResults.NotFound()を返し、何も追加しません。
  3. それ以外の場合は、その位置にnew TaskItem(id, input.Title, input.Done)を格納し、Results.Okで応答します。PUT /api/tasks/1に{ "title": "Write the final brief", "done": true }を送ると、200と次の内容が返ります:
    { "id": 1, "title": "Write the final brief", "done": true }

試してみましょう:「実行」を押し、PUTを選び、パスに/api/tasks/1、本文に上記の内容を指定して、「送信」を押します。200と上記のタスクが返ります。GET /api/tasks/1を送信すると、新しいタイトルが返ります。{ "title": "Book the big room" }を指定して/api/tasks/2にPUTを送信すると、タスク2は完了済みでしたが、本文ではdoneが省略されているため、"done": falseが返ります。/api/tasks/99へのPUTは404を返します。

自分で試してみよう

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

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    new(3, "Send the invoice", false),
};
var nextId = 4;

app.MapGet("/api/tasks", () => tasks);

app.MapGet("/api/tasks/{id:int}", (int id) =>
{
    var task = tasks.Find(t => t.Id == id);
    return task is null ? Results.NotFound() : Results.Ok(task);
});

app.MapPost("/api/tasks", (TaskInput input) =>
{
    var task = new TaskItem(nextId++, input.Title, input.Done);
    tasks.Add(task);
    return Results.Created($"/api/tasks/{task.Id}", task);
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(string Title, bool Done);

REST APIのすべてのレッスン