Menu
CoddyTech

Replacing with PUT

Part of the REST APIs section of Coddy's ASP.NET Core journey. Lesson 3 of 20.

PUT replaces an item. The body is the item's whole new state, sent to the item's own URL, and a field the body leaves out gets its default value. Sending the same PUT twice gives the same result, so PUT is idempotent: a client may retry it after a timeout. POST is not, since a second POST adds a second item.

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]);
});

The id comes from the path, never from the body, so a client cannot move a product to another id. FindIndex returns the item's position in the list, or -1 when nothing matches, and products[index] = ... stores the new version in its place.

challenge icon

Challenge

Easy

Let clients replace a task.

  1. In Program.cs, map PUT /api/tasks/{id:int} with an int id and a TaskInput input parameter. The body has the same shape as a POST body.
  2. Find the task's position with tasks.FindIndex. When it is -1, answer Results.NotFound() and add nothing.
  3. Otherwise store new TaskItem(id, input.Title, input.Done) at that position and answer it with Results.Ok. PUT /api/tasks/1 with { "title": "Write the final brief", "done": true } answers 200 and:
    { "id": 1, "title": "Write the final brief", "done": true }

Try it: press Run, choose PUT, path /api/tasks/1, the body above, and Send: 200 and the task above. Send GET /api/tasks/1: the new title. Send PUT /api/tasks/2 with { "title": "Book the big room" }: task 2 was done, but the body left done out, so it comes back "done": false. A PUT to /api/tasks/99 answers 404.

Try it yourself

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);

All lessons in REST APIs