Menu
CoddyTech

Paging

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

An orders API with 10,000 orders cannot answer them all at once. Paging answers one slice: GET /api/orders?page=3&pageSize=20 is orders 41 to 60. The client also needs the total, to draw "page 3 of 500", and a header carries it without changing the body's shape.

app.MapGet("/api/orders", (HttpResponse response, int page = 1, int pageSize = 20) =>
{
    var matching = orders.ToList();
    response.Headers["X-Total-Count"] = matching.Count.ToString();
    return Results.Ok(matching.Skip((page - 1) * pageSize).Take(pageSize));
});

A default value makes a query parameter optional. An HttpResponse parameter is the response being built, so you can set a header before you return. X-Total-Count counts the orders that match the filters, before paging. Refuse a page below 1 and cap the page size, so no client can ask for everything at once.

challenge icon

Challenge

Medium

Answer the tasks one page at a time, and say how many there are in total.

  1. Add three parameters to the GET /api/tasks lambda, after sort: HttpResponse response, int page = 1 and int pageSize = 10.
  2. In the errors dictionary, add Page starts at 1. under page when page is below 1, and Page size is 1 to 50. under pageSize when pageSize is outside 1 to 50.
  3. After filtering and sorting, turn the result into a list. Set the header X-Total-Count to its count, then answer only the page: skip (page - 1) * pageSize tasks and take pageSize.

GET /api/tasks?page=2&pageSize=2 answers only task 3, with X-Total-Count: 3. A page past the end answers 200 and [].

Try it: press Run and send GET /api/tasks?page=2&pageSize=2: task 3, and the Headers tab shows X-Total-Count: 3. Send GET /api/tasks?done=false&pageSize=1: task 1 and X-Total-Count: 2. Send GET /api/tasks?page=0&pageSize=99: 400 with both errors.

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;

bool TitleTaken(string title, int exceptId) =>
    tasks.Any(t => t.Id != exceptId && string.Equals(t.Title, title, StringComparison.OrdinalIgnoreCase));

app.MapGet("/api/tasks", (bool? done, string? search, string? sort) =>
{
    var errors = new Dictionary<string, string[]>();
    if (sort is not null && sort != "id" && sort != "title")
        errors["sort"] = ["Sort by id or title."];
    if (errors.Count > 0) return Results.ValidationProblem(errors);

    IEnumerable<TaskItem> result = tasks;
    if (done is not null) result = result.Where(t => t.Done == done);
    if (!string.IsNullOrWhiteSpace(search))
        result = result.Where(t => t.Title.Contains(search, StringComparison.OrdinalIgnoreCase));
    if (sort == "title") result = result.OrderBy(t => t.Title);
    return Results.Ok(result);
});

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);
    if (TitleTaken(input.Title, 0))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    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();
    if (TitleTaken(input.Title, id))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    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();
    if (patch.Title is not null && TitleTaken(patch.Title, id))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    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);
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in REST APIs