Deleting with DELETE
Part of the REST APIs section of Coddy's ASP.NET Core journey. Lesson 5 of 20.
DELETE removes an item. When it worked, the answer is 204 No Content: success with an empty body, since nothing is left to show. When the item does not exist, the answer is 404.
app.MapDelete("/api/notes/{id:int}", (int id) =>
{
var removed = notes.RemoveAll(n => n.Id == id);
return removed == 0 ? Results.NotFound() : Results.NoContent();
});RemoveAll returns how many items it removed. A deleted id is never given to a new item: a client that kept the URL /api/notes/7 must get 404 later, not someone else's note. A counter gives you that. The largest id plus one does not: after the newest note is deleted, the next note would take its id.
Challenge
EasyLet clients delete a task.
- In
Program.cs, mapDELETE /api/tasks/{id:int}. - Remove the task with
tasks.RemoveAll. When it removed nothing, answerResults.NotFound(); otherwise answerResults.NoContent(), status 204 with an empty body. - Keep giving ids from
nextId: afterDELETE /api/tasks/3, the next new task gets id 4, not 3.
Try it: press Run, choose DELETE, path /api/tasks/3, and Send: 204 and an empty body. Send GET /api/tasks: two tasks left. Send DELETE /api/tasks/3 again: 404, because the first delete is replayed before it. POST { "title": "Order new chairs" } to /api/tasks: it gets id 4.
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.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
var index = tasks.FindIndex(t => t.Id == id);
if (index == -1) return Results.NotFound();
var task = tasks[index];
tasks[index] = task with
{
Title = patch.Title ?? task.Title,
Done = patch.Done ?? task.Done,
};
return Results.Ok(tasks[index]);
});
app.Run();
record TaskItem(int Id, string Title, bool Done);
record TaskInput(string Title, bool Done);
record TaskPatch(string? Title, bool? Done);
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST