Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 52 ยท Projects

Project: Todo API

Build a complete Todo API with minimal APIs: CRUD endpoints, validation, problem details, typed results and an in-memory store, tested end to end.

It is time to put the pieces together. In this project you build a small but complete REST API for a todo list: create, read, update and delete items, filter the list, reject bad input with helpful errors, and return consistent error responses. Everything runs inside one program that starts Kestrel on a loopback port and exercises the API with HttpClient, so you can see every request and response.

The project uses only ideas from earlier lessons: minimal API endpoints, route groups, parameter binding, results, validation and error handling. If any step feels fast, revisit the lesson it links to.

The design

Before writing code, decide the contract. A REST API is a set of resources (nouns) and a small set of verbs.

Method Path Meaning Success Failure
GET /todos List todos (filter with ?done= and ?q=) 200
GET /todos/{id} Get one todo 200 404
POST /todos Create a todo 201 + Location 400 validation
PUT /todos/{id} Replace a todo 200 400, 404
PATCH /todos/{id} Change some fields 200 400, 404
DELETE /todos/{id} Delete a todo 204 404

Errors use Problem Details (RFC 9457, application/problem+json): a standard JSON shape with status, title and, for validation, an errors object. Clients can handle every error the same way.

flowchart LR
    R["HTTP request"] --> E["UseExceptionHandler<br/>catches unexpected errors"]
    E --> S["UseStatusCodePages<br/>problem body for empty 4xx"]
    S --> G["MapGroup /todos"]
    G --> H["Endpoint handler<br/>binds, validates"]
    H --> T[("TodoStore<br/>ConcurrentDictionary")]
    H --> X["TypedResults<br/>Ok, Created, NotFound, ValidationProblem"]

Two small middleware guarantee consistent error bodies; handlers return typed results; the store holds the data.

Step 1: the model and the store

A todo is an immutable record. The store hides the dictionary behind intention-revealing methods, which keeps the endpoints short and makes it easy to swap in a database later (see Data Access without an ORM).

C#
public record Todo(int Id, string Title, bool IsDone, int Priority);

public class TodoStore
{
    private readonly ConcurrentDictionary<int, Todo> items = new();
    private int lastId;

    public Todo Add(string title, int priority)
    {
        int id = Interlocked.Increment(ref lastId);   // thread-safe id generation
        var todo = new Todo(id, title, false, priority);
        items[id] = todo;
        return todo;
    }
    // Find, Query, Update, Remove ...
}

The store is registered as a singleton, since it holds the data for the whole process. Because many requests run at once, it must be thread-safe: ConcurrentDictionary plus Interlocked.Increment give that without explicit locks. The Update method retries with TryUpdate so two simultaneous edits of one todo cannot silently overwrite each other's work.

Let us start with a first slice: only the store and two endpoints, so you can see the pieces working before adding validation.

C# Step 1: store, list and create

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This works, but it trusts its input completely. A request with {"title":""} or {"priority":99} would be stored. Real APIs validate at the edge.

Step 2: validation and problem details

Binding turns JSON into a CreateTodo; it does not check meaning. We write one small validation function that returns a dictionary of field names to messages, and respond with TypedResults.ValidationProblem(errors), which produces a 400 with the standard errors shape:

C#
static Dictionary<string, string[]> Validate(string? title, int? priority)
{
    var errors = new Dictionary<string, string[]>();
    if (string.IsNullOrWhiteSpace(title))
        errors["title"] = ["Title is required."];
    else if (title.Trim().Length > 100)
        errors["title"] = ["Title must be 100 characters or fewer."];
    if (priority is < 1 or > 3)
        errors["priority"] = ["Priority must be 1 (high), 2 (normal) or 3 (low)."];
    return errors;
}

The same function is used by POST and PUT, so the rules live in one place. For larger models, use data annotations or a validation filter, as shown in Model Validation.

Two middleware complete the error story. AddProblemDetails() plus UseExceptionHandler() turns an unexpected exception into a 500 with a problem body and no stack trace or message leaked (in production). UseStatusCodePages() fills in a problem body for empty error responses such as a 404 for an unknown path or a 405.

Step 3: typed results

Instead of IResult, each handler declares exactly which responses it can produce with a union such as Results<Ok<Todo>, NotFound>. The compiler then checks that every code path returns one of them, and OpenAPI generation (see OpenAPI and Versioning) documents them automatically. Handlers are also easier to unit test, because you can assert on the returned type.

C#
todos.MapGet("/{id:int}", Results<Ok<Todo>, NotFound> (int id, TodoStore store) =>
    store.Find(id) is { } todo ? TypedResults.Ok(todo) : TypedResults.NotFound());

The :int route constraint means /todos/abc never reaches the handler; it simply does not match the route and returns 404.

The complete API

Here is the whole program. Read it top to bottom, then run it: the client section at the end walks through a realistic session, including every failure mode.

C# The complete Todo API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Reading the results

Walk through the output section by section.

  • Create returns 201 Created with a Location header pointing at the new resource and the stored todo as the body. The server, not the client, assigns the id, and a missing priority defaults to 2.
  • Read and filter use query parameters bound from the URL: ?done=true binds to bool?, ?q=tests to string?. When a parameter is absent it is null and the filter is skipped, so one endpoint serves every combination.
  • PATCH changes only the fields the client sent (current with { ... } copies the record and replaces some properties), while PUT replaces the whole todo. That is the standard difference: PUT is "here is the new state", PATCH is "apply these changes".
  • DELETE returns 204 No Content and a second lookup returns 404. Deleting twice would give a 404 the second time; some APIs prefer to make delete idempotent and return 204 always, which is also reasonable. Pick one rule and document it.
  • Failures all share the problem details shape. The validation response lists every problem at once under errors, keyed by field, so a form can show all messages in one round trip. Malformed JSON gives a plain 400 before your code runs, an unmatched route (/todos/abc) gives 404, and the deliberate crash gives 500 with a generic title: the text secret internal detail never reaches the client.

The traceId field that ASP.NET Core adds to every problem response is stripped in the demo only because it changes on every run. In production it is valuable: users can quote it in a support request and you can find the matching log lines (see Observability in Production).

Design decisions worth knowing

Why records for DTOs? Request types (CreateTodo, ReplaceTodo, PatchTodo) are separate from the stored Todo. The client must not be able to set the Id, and each operation accepts a slightly different shape: PATCH fields are all optional, PUT requires the title. See DTOs, Records and Mapping.

Why nullable properties on input records? string? Title lets a missing title bind as null, so our validation answers with a friendly message instead of a generic binding failure.

Why Update(id, Func<Todo, Todo>)? It encapsulates the read-modify-write loop. Two clients patching the same todo at the same moment are both applied: if the compare-and-swap in TryUpdate fails, the function runs again on the fresh value. This is optimistic concurrency, the same idea EF Core uses with concurrency tokens.

Why a route group? MapGroup("/todos") removes the repeated prefix and is the place to attach shared behavior later, such as .RequireAuthorization() or .WithTags("Todos") (see Route Groups).

Taking it further

The API is deliberately small. Good next steps, each backed by a lesson:

  1. Move the endpoints out of Program.cs into an extension method MapTodoEndpoints(this IEndpointRouteBuilder), and keep Program.cs to the wiring.
  2. Replace the dictionary with a database behind an ITodoRepository interface (EF Core Overview).
  3. Add paging (?page=2&pageSize=20) and sorting to the list endpoint.
  4. Protect it so each user sees only their own todos (Project: Notes API with Authentication does exactly that).
  5. Document it with OpenAPI so clients can generate code (OpenAPI and Versioning).
  6. Test it the way this lesson did, with a real server on loopback and HttpClient (Testing ASP.NET Core Apps).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which status code and header should a successful POST that creates a todo return?

    201 Created tells the client a new resource exists, and Location says where to find it.
  2. 2. What is the difference between PUT and PATCH in this API?

    PUT carries the complete new state; PATCH carries a partial change that is merged into the current state.
  3. 3. Why is the TodoStore registered as a singleton and built on ConcurrentDictionary?

    One instance serves all requests. Because requests run in parallel, the collection and id generation must be thread-safe. The data still disappears when the process stops.
  4. 4. A client sends a body with an empty title and priority 9. What does the API return?

    The validation function collects all errors and the handler returns TypedResults.ValidationProblem, a 400 with an errors object keyed by field.
  5. 5. What does a handler declared as returning Results<Ok<Todo>, NotFound> give you?

    The union type lists exactly what the endpoint can return, so the compiler verifies every path and OpenAPI generation can describe them.

Summary

  • Design the contract first: resources, verbs, success codes and failure codes.
  • A route group, typed results and a small store keep a minimal API readable.
  • Validate at the edge and return all errors at once as ValidationProblem; share one validation function between POST and PUT.
  • AddProblemDetails, UseExceptionHandler and UseStatusCodePages give every error the same JSON shape without leaking internals.
  • Use separate input records from stored entities, and a thread-safe singleton store with optimistic updates.
  • A real Kestrel server plus HttpClient is a complete end-to-end test of the whole pipeline.

Next: Project: URL Shortener