10.12 — Minimal APIs: Syntax, Filters and When to Choose Them¶
← Roadmap · Section: 10. Web API Design and REST Prev: 10.11 DTOs and mapping · Next: 10.13 Idempotency keys and ETags
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Minimal APIs define endpoints as lambdas mapped directly onto routes, with no controller class.
- Faster — no controller instantiation, no action-invoker pipeline, no reflection-heavy model binding. Meaningfully lower per-request overhead.
TypedResults, notResults— the typed version gives you a testable return type and free OpenAPI metadata.- Endpoint filters replace action filters, and the mental model is different: they are nested wrappers, not a pipeline of hooks.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Minimal API | a programming model | Endpoints as lambdas mapped to routes, no controller. |
MapGet / MapPost / … |
extension methods | Register a handler for a route and verb. |
Results |
a static class | Factory for IResult values. Untyped. |
TypedResults |
a static class | Same factories, typed return values. |
IResult |
an interface | The minimal-API answer to IActionResult. |
Results<T1, T2> |
a union type | Declares multiple possible typed results from one handler. |
| Route group | MapGroup() |
A prefix plus shared metadata for several endpoints. |
| Endpoint filter | IEndpointFilter |
The minimal-API equivalent of an action filter. |
[AsParameters] |
an attribute | Bind several parameters into one struct or record. |
WithOpenApi() / Produces<T>() |
builder methods | Attach OpenAPI metadata. |
AddEndpointsApiExplorer |
a DI call | Makes minimal endpoints visible to OpenAPI. |
The concept¶
Controllers carry machinery: a class, a base class, attribute routing, an action invoker, a filter pipeline, model binding by reflection. For an endpoint that reads an ID and returns a row, most of that is overhead.
// Controller — 12 lines of scaffolding for one line of work
[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
private readonly IOrderService _orders;
public OrdersController(IOrderService orders) => _orders = orders;
[HttpGet("{id:int}")]
public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct)
{
var order = await _orders.FindAsync(id, ct);
return order is null ? NotFound() : Ok(order);
}
}
// Minimal API — the same endpoint
app.MapGet("/api/orders/{id:int}", async (int id, IOrderService orders, CancellationToken ct) =>
await orders.FindAsync(id, ct) is { } order
? TypedResults.Ok(order)
: Results.NotFound());
The performance difference is real and not just aesthetic. No controller instance per request, no action invoker, and binding is source-generated rather than reflected. For a hot endpoint that matters; for one called twice a minute it does not.
⚠️ "Minimal APIs are faster" is only half an answer. The follow-up is why — no controller activation, no filter pipeline unless you add one, and compile-time-known parameter binding.
How it works¶
Results vs TypedResults — get this right¶
// ⚠️ Returns IResult. Untestable without inspecting the response, and OpenAPI
// cannot infer what a success looks like.
app.MapGet("/orders/{id:int}", async (int id, IOrderService s, CancellationToken ct) =>
{
var order = await s.FindAsync(id, ct);
return order is null ? Results.NotFound() : Results.Ok(order);
});
// ✅ Returns Results<Ok<OrderDto>, NotFound>. The types ARE the contract.
app.MapGet("/orders/{id:int}",
async Task<Results<Ok<OrderDto>, NotFound>> (int id, IOrderService s, CancellationToken ct) =>
{
var order = await s.FindAsync(id, ct);
return order is null ? TypedResults.NotFound() : TypedResults.Ok(order);
});
Two things fall out of the typed version:
Tests read normally. A unit test can assert on the returned type and its Value without
building an HttpContext or parsing a response body (20.6).
OpenAPI is inferred. Results<Ok<OrderDto>, NotFound> tells the generator that this endpoint
returns 200 with an OrderDto or a 404 — no Produces<T>() needed
(10.9).
⚠️ TypedResults should be the default. Results exists mostly for cases where the union type
gets unwieldy.
Route groups¶
Without grouping, minimal APIs sprawl across Program.cs. MapGroup fixes both the repetition and
the organisation:
var orders = app.MapGroup("/api/orders")
.WithTags("Orders") // groups them in Swagger
.RequireAuthorization() // applies to EVERY endpoint in the group
.AddEndpointFilter<ValidationFilter>();
orders.MapGet("/", ListOrders);
orders.MapGet("/{id:int}", GetOrder);
orders.MapPost("/", CreateOrder);
orders.MapDelete("/{id:int}", DeleteOrder).RequireAuthorization("Admin");
⚠️ Group-level RequireAuthorization() applies to everything in the group, including endpoints
added later by someone who did not read the group declaration. Usually what you want — but an
endpoint that must be public needs .AllowAnonymous(), which wins regardless of order
(8.9).
Endpoint filters — a different mental model¶
An action filter has separate OnActionExecuting and OnActionExecuted hooks. An endpoint filter
is a single wrapper — you call next and everything after that call is the "after" half:
public sealed class ValidationFilter<T> : IEndpointFilter where T : class
{
private readonly IValidator<T> _validator;
public ValidationFilter(IValidator<T> validator) => _validator = validator;
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var argument = context.Arguments.OfType<T>().FirstOrDefault();
if (argument is null) return await next(context);
var result = await _validator.ValidateAsync(argument);
if (!result.IsValid)
{
// Short-circuit: return without calling next, and the handler never runs
return TypedResults.ValidationProblem(result.ToDictionary());
}
return await next(context); // everything after this line runs AFTER the handler
}
}
⚠️ Minimal APIs have no automatic model validation. [ApiController]'s automatic 400 does not
exist here — data annotations on a parameter type are not checked. You add a filter, or use the
.NET 10 validation support, or validate by hand. This is the single most common surprise when
moving from controllers (10.4).
⚠️ Filter order is registration order, and it wraps. Filters registered on the group run outside filters registered on the endpoint (12.7).
Binding, and where it differs¶
| Parameter | Bound from |
|---|---|
| Matches a route token | Route |
| Simple type, no match | Query string |
| Complex type | Body |
| Registered in DI | Services |
HttpContext, ClaimsPrincipal, CancellationToken |
Special-cased |
Has TryParse or BindAsync |
Custom binding |
⚠️ Only one body parameter, same as controllers. And a complex type intended to come from the
query needs [AsParameters] or explicit [FromQuery]:
// One record holding many query parameters — much cleaner than eight arguments
public readonly record struct OrderSearch(
[FromQuery] string? Status,
[FromQuery] int Page = 1,
[FromQuery] int PageSize = 20);
app.MapGet("/api/orders", async ([AsParameters] OrderSearch search,
IOrderService orders, CancellationToken ct)
=> TypedResults.Ok(await orders.SearchAsync(search, ct)));
The deeper detail — when to choose which¶
| Situation | Choose |
|---|---|
| Small service, few endpoints | Minimal |
| Native AOT / serverless / cold-start sensitive | Minimal |
| Highest throughput on hot paths | Minimal |
| Large API, many endpoints, several teams | ⚠️ Controllers |
| Heavy use of MVC filters and conventions | Controllers |
| Existing controller-based codebase | Controllers — do not mix for its own sake |
| Views or Razor Pages alongside | Controllers |
⚠️ The main practical objection to minimal APIs is organisation. Fifty endpoints as lambdas in
Program.cs is unreadable. The answer is extension methods per feature:
public static class OrderEndpoints
{
public static IEndpointRouteBuilder MapOrderEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/api/orders").WithTags("Orders").RequireAuthorization();
group.MapGet("/{id:int}", GetOrder).WithName("GetOrder");
group.MapPost("/", CreateOrder);
return app;
}
// Named static methods, not inline lambdas — testable and readable
private static async Task<Results<Ok<OrderDto>, NotFound>> GetOrder(
int id, IOrderService orders, CancellationToken ct)
=> await orders.FindAsync(id, ct) is { } o
? TypedResults.Ok(o)
: TypedResults.NotFound();
}
With that structure, most of the "controllers are more organised" argument evaporates — and saying so is a better answer than picking a side.
⚠️ The performance gap has also narrowed. Controllers have improved with each release, and for most applications the difference is not what should drive the decision. The AOT and cold-start story is the more durable argument (21.10).
Code¶
A feature module end to end:
public static class OrderEndpoints
{
public static IEndpointRouteBuilder MapOrderEndpoints(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/api/orders")
.WithTags("Orders")
.RequireAuthorization()
.AddEndpointFilter<RequestLoggingFilter>();
group.MapGet("/", ListOrders)
.WithName("ListOrders")
.WithSummary("Lists orders for the current customer.");
group.MapGet("/{id:int}", GetOrder)
.WithName("GetOrder");
group.MapPost("/", CreateOrder)
.AddEndpointFilter<ValidationFilter<CreateOrderRequest>>()
.WithName("CreateOrder");
group.MapDelete("/{id:int}", DeleteOrder)
.RequireAuthorization("OrdersAdmin"); // stricter than the group
// Public — AllowAnonymous overrides the group's RequireAuthorization
group.MapGet("/status", () => TypedResults.Ok(new { status = "ok" }))
.AllowAnonymous();
return app;
}
private static async Task<Ok<PagedResult<OrderDto>>> ListOrders(
[AsParameters] OrderSearch search,
IOrderService orders,
CancellationToken ct)
=> TypedResults.Ok(await orders.SearchAsync(search, ct));
// The union type documents every outcome AND drives the OpenAPI schema
private static async Task<Results<Ok<OrderDto>, NotFound, ForbidHttpResult>> GetOrder(
int id,
IOrderService orders,
ClaimsPrincipal user, // special-cased — bound automatically
CancellationToken ct)
{
var order = await orders.FindAsync(id, ct);
if (order is null) return TypedResults.NotFound();
if (order.CustomerId != user.GetCustomerId()) return TypedResults.Forbid();
return TypedResults.Ok(order);
}
private static async Task<Results<Created<OrderDto>, ValidationProblem, Conflict<ProblemDetails>>>
CreateOrder(CreateOrderRequest request, IOrderService orders, CancellationToken ct)
{
var result = await orders.CreateAsync(request, ct);
if (result.Status == CreateStatus.DuplicateReference)
{
return TypedResults.Conflict(new ProblemDetails
{
Title = "Duplicate order reference",
Status = StatusCodes.Status409Conflict
});
}
// Created<T> sets the Location header — the minimal-API CreatedAtRoute
return TypedResults.Created($"/api/orders/{result.Order!.Id}", result.Order);
}
private static async Task<NoContent> DeleteOrder(
int id, IOrderService orders, CancellationToken ct)
{
await orders.DeleteAsync(id, ct);
return TypedResults.NoContent();
}
}
A filter that adds behaviour before and after the handler:
public sealed class RequestLoggingFilter : IEndpointFilter
{
private readonly ILogger<RequestLoggingFilter> _log;
public RequestLoggingFilter(ILogger<RequestLoggingFilter> log) => _log = log;
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var stopwatch = Stopwatch.StartNew();
var name = context.HttpContext.GetEndpoint()?.DisplayName ?? "unknown";
try
{
var result = await next(context); // ← the handler runs here
_log.LogInformation("{Endpoint} completed in {Elapsed}ms",
name, stopwatch.ElapsedMilliseconds);
return result;
}
catch (Exception ex)
{
// ⚠️ Log and rethrow. Swallowing it here turns a 500 into a silent 200.
_log.LogError(ex, "{Endpoint} failed after {Elapsed}ms",
name, stopwatch.ElapsedMilliseconds);
throw;
}
}
}
Interview questions¶
Q: What are minimal APIs and when would you use them?
Endpoints defined as lambdas mapped straight onto routes, with no controller class. They are faster
per request — no controller instantiation, no action invoker, no reflection-based binding — and
they work under Native AOT, which matters for serverless and cold starts. I would reach for them on
a small service, on genuinely hot endpoints, or anywhere AOT is in play. For a large API across
several teams, controllers still have better conventions and organisation out of the box, though
that gap closes a lot if you organise minimal endpoints into per-feature extension methods rather
than piling them into Program.cs.
Q: What is the difference between Results and TypedResults?
Results.Ok(x) returns an untyped IResult; TypedResults.Ok(x) returns Ok<T>. The typed
version buys two things: a unit test can assert on the returned type and its value without building
an HttpContext or parsing a response, and OpenAPI can infer the response schema from the
signature — so declaring Results<Ok<OrderDto>, NotFound> documents both outcomes with no
attributes. TypedResults should be the default.
Q: What is the biggest surprise moving from controllers?
No automatic model validation. [ApiController] gives you an automatic 400 when ModelState is
invalid; minimal APIs have nothing equivalent, so data annotations on a parameter type are simply
not checked and invalid input reaches your handler as nulls and zeroes. You add an endpoint filter,
or validate explicitly. The related one is that endpoint filters are a different shape from action
filters — one wrapper method where you call next, rather than separate before and after hooks,
and short-circuiting means returning without calling next at all.
Q: How do you keep them organised?
Extension methods per feature, each returning IEndpointRouteBuilder so they chain, with a
MapGroup inside setting the prefix, tags, authorization and shared filters. Handlers are named
static methods rather than inline lambdas, which makes them readable and directly unit testable.
Program.cs then reads as app.MapOrderEndpoints().MapCustomerEndpoints(). Most of the "minimal
APIs do not scale" objection is really an objection to fifty lambdas in one file.
Traps ⚠️¶
- No automatic model validation. Data annotations are not checked.
Resultsinstead ofTypedResultsloses testability and OpenAPI inference.- All endpoints in
Program.cs— unreadable past a dozen. - Group
RequireAuthorization()silently applies to endpoints added later. - Complex type on a
GETbinds from the body. Use[AsParameters]. - Only one body parameter — two complex types throw at startup.
- Swallowing an exception in a filter turns a 500 into a silent success.
- Missing
AddEndpointsApiExplorer()hides endpoints from OpenAPI. - No
[ApiController]conventions — no inference, no automaticProblemDetails. - MVC filters do not apply. Endpoint filters are a separate mechanism.
- Mixing both models without a reason doubles the conventions in one codebase.
Related¶
- 10.4
[ApiController]— the conventions you give up - 10.9 OpenAPI — how
TypedResultsfeeds the document - 10.3 Status codes — the
TypedResultsfactories - 8.9 Route groups —
MapGroupin depth - 12.7 Endpoint filters — the filter model in full
- 21.7 Minimal APIs deep dive — the advanced material
- 21.10 Native AOT — the durable argument
- 20.6 Unit testing ASP.NET — testing typed results