Filtering
Part of the REST APIs section of Coddy's ASP.NET Core journey. Lesson 10 of 20.
Clients often want part of a collection: the open tasks, the products in stock. The REST way is a filter in the query string of the same URL, GET /api/products?inStock=true, not a new path for each subset.
app.MapGet("/api/products", (bool? inStock) =>
{
IEnumerable<Product> result = products;
if (inStock is not null) result = result.Where(p => p.InStock == inStock);
return Results.Ok(result);
});A lambda parameter that is not in the route is read from the query string. Make it nullable, so a missing inStock is null and the filter is skipped. Where makes a filtered sequence and leaves products as it was. A value that is not a bool, such as ?inStock=maybe, never reaches the lambda: ASP.NET Core answers 400.
Challenge
EasyLet clients ask for the open or the done tasks.
- In
Program.cs, give theGET /api/taskslambda abool? doneparameter. Its body now needs braces and areturn. - Start from
IEnumerable<TaskItem> result = tasks;. Whendoneis notnull, keep only the tasks whoseDoneequals it, withWhere. - Answer
Results.Ok(result). Withoutdone, every task comes back, as before.
GET /api/tasks?done=false answers tasks 1 and 3:
[ { "id": 1, "title": "Write the project brief", "done": false },
{ "id": 3, "title": "Send the invoice", "done": false } ]Try it: press Run and send GET /api/tasks?done=false: the two tasks above. Send GET /api/tasks?done=true: only task 2. Send GET /api/tasks: all three. Send GET /api/tasks?done=maybe: 400, from ASP.NET Core itself.
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", () => 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);
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);
This lesson includes a short quiz. Start the lesson to answer it and track your progress.