Partial Updates with PATCH
Part of the REST APIs section of Coddy's ASP.NET Core journey. Lesson 4 of 20.
PATCH changes only the fields the body sends. To tell a field that was left out from one that was set, make every property of the patch record nullable: a missing field binds to null.
record ProfilePatch(string? Name, string? City);
profiles[index] = profile with
{
Name = patch.Name ?? profile.Name,
City = patch.City ?? profile.City,
};with copies a record and changes the properties you list. ?? keeps the old value when the patch holds null. A bool? works the same way: false is a value the client sent, and null means it sent nothing. So { "city": "Lyon" } moves the profile and keeps its name.
Challenge
EasyLet clients change one field of a task, such as ticking it done, without sending the title again.
- At the bottom of
Program.cs, declarerecord TaskPatch(string? Title, bool? Done); - Map
PATCH /api/tasks/{id:int}with anint idand aTaskPatch patch. AnswerResults.NotFound()when no task has the id. - Otherwise store a copy of the task made with
with, where each property takes the patch's value, or keeps the task's own when the patch hasnull. Answer the changed task withResults.Ok.
PATCH /api/tasks/1 with { "done": true } answers 200 and:
{ "id": 1, "title": "Write the project brief", "done": true }Try it: press Run, choose PATCH, path /api/tasks/1, the body { "done": true }, and Send: the answer above, with the title kept. Send PATCH /api/tasks/2 with { "title": "Book the big room" }: the new title, and "done": true stays. PATCH /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.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
var index = tasks.FindIndex(t => t.Id == id);
if (index == -1) return Results.NotFound();
tasks[index] = new TaskItem(id, input.Title, input.Done);
return Results.Ok(tasks[index]);
});
app.Run();
record TaskItem(int Id, string Title, bool Done);
record TaskInput(string Title, bool Done);
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST