Menu
CoddyTech

Conflicts

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

A second user called "Ada" makes logins ambiguous, yet the body is valid. That is 409 Conflict: the request clashes with what is already stored. A 400 means the body itself is wrong; a 409 means it is fine but cannot be applied now.

bool NameTaken(string name, int exceptId) =>
    users.Any(u => u.Id != exceptId &&
        string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));

if (NameTaken(input.Name, id))
    return Results.Problem(title: "That name is taken.", statusCode: 409);

People read "Ada" and "ada" as the same name, so compare with StringComparison.OrdinalIgnoreCase. When a request renames a user, leave that user out of the search: otherwise saving a form without changing the name conflicts with itself. Results.Problem answers in the problem details shape, with your title and status.

challenge icon

Challenge

Medium

Two tasks called "Send the invoice" make the list confusing. Refuse a title another task already has.

  1. In Program.cs, below nextId, write a local function bool TitleTaken(string title, int exceptId): true when a task other than exceptId has the title, ignoring case.
  2. In POST, after the validation check, answer Results.Problem(title: "A task with this title already exists.", statusCode: 409) when the title is taken, and add nothing. POST has no task to leave out, so pass 0.
  3. Do the same in PUT, passing the task's id, so a task may keep its own title or change its capitals.
  4. In PATCH, check only when the body sends a title (patch.Title is not null).

A refused request changes nothing. The 409 body is:

{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.10", "title": "A task with this title already exists.", "status": 409, "traceId": "..." }

Try it: press Run and POST { "title": "book the MEETING room" } to /api/tasks: 409, because task 2 has that title. PUT { "title": "Book the Meeting Room", "done": false } to /api/tasks/2: 200, its own title. PATCH /api/tasks/3 with { "title": "Write the project brief" }: 409. POST { "title": "Order new chairs" }: 201 with id 4.

Try it yourself

using System.ComponentModel.DataAnnotations;

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

app.UseExceptionHandler();
app.UseStatusCodePages();

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 errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    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 errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    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.MapDelete("/api/tasks/{id:int}", (int id) =>
{
    var removed = tasks.RemoveAll(t => t.Id == id);
    return removed == 0 ? Results.NotFound() : Results.NoContent();
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(
    [property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
    bool Done);
record TaskPatch(string? Title, bool? Done);

All lessons in REST APIs