Minimal APIs
Minimal APIs connect a route directly to a handler function with MapGet/MapPost, without controller classes. With TypedResults, MapGroup, endpoint filters and .NET 10 AddValidation they are a full production option, recommended for new projects.
47.1 Why is it used?
- Less ceremony: no controller class, a route maps straight to a lambda or static method.
- Better performance and a small, clean Program.cs when endpoints live in extension methods.
- TypedResults put the status code into the return type, so the compiler and OpenAPI both know every result.
- Groups, filters, validation and OpenAPI cover what serious apps need.
47.2 The bug: 200 OK with null
var builder = WebApplication.CreateBuilder(args);builder.Services.AddSingleton<ProductStore>();var app = builder.Build(); app.MapGet("/api/products/{id}", (int id, ProductStore store) => store.Find(id)?.ToDto()); app.Run();$ curl -i localhost:5047/api/products/99HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8Server: Kestrelnull- A handler that returns just an object is written as JSON and always gets 200, even when the value is null.
- Controllers gave 204 for null, here it is 200 + null: both are the wrong signal; it should be 404.
- Step 1
1.Handler returns just an object
- Step 2
2.store.Find(99) is null -> ?.ToDto() is null
- Step 3
3.Minimal API writes JSON with status 200
- Step 4
4.Client gets 200 + body null instead of 404
Needed: data + status = TypedResults
47.3 Fix: TypedResults
using Microsoft.AspNetCore.Http.HttpResults; static Results<Ok<ProductDto>, NotFound> GetById( int id, ProductStore store){ var product = store.Find(id); if (product is null) return TypedResults.NotFound(); return TypedResults.Ok(product.ToDto());}$ curl -i localhost:5047/api/products/1HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{"id":1,"name":"Mixer Grinder","price":2499} $ curl -i localhost:5047/api/products/99HTTP/1.1 404 Not FoundContent-Length: 0Server: Kestrel- Results<Ok<ProductDto>, NotFound> works like a union type: the endpoint returns only one of these two.
- TypedResults.NotFound() and TypedResults.Ok(dto) carry the status code with the data.
- The handler is a separate static method, so it is easy to test.
47.4 Program.cs + MapGroup
var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton<ProductStore>();builder.Services.AddValidation(); var app = builder.Build(); app.MapProductEndpoints();app.MapUploadEndpoints(); app.Run();public static class ProductEndpoints{ public static void MapProductEndpoints( this IEndpointRouteBuilder app) { var group = app.MapGroup("/api/products") .AddEndpointFilter<TimingFilter>(); group.MapGet("/", GetAll); group.MapGet("/{id:int}", GetById); group.MapPost("/", Create); group.MapDelete("/{id:int}", Delete); }}$ curl -i localhost:5047/api/productsHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8[ {"id":1,"name":"Mixer Grinder","price":2499}, {"id":2,"name":"Steel Bottle","price":399}]- MapProductEndpoints is an extension method holding all product endpoints, so Program.cs stays small.
- MapGroup("/api/products") gives one prefix; each endpoint only adds a relative route and a handler name.
- Anything added to the group (like AddEndpointFilter<TimingFilter>()) applies to every endpoint in it.
47.5 POST: 201 + Location
static Created<ProductDto> Create( CreateProductRequest request, ProductStore store){ var dto = store .Add(request.Name, request.Price).ToDto(); return TypedResults.Created( $"/api/products/{dto.Id}", dto);}$ curl -i localhost:5047/api/products \ -H "Content-Type: application/json" \ -d '{"name":"Pressure Cooker","price":1899}'HTTP/1.1 201 CreatedContent-Type: application/json; charset=utf-8Location: /api/products/3{"id":3,"name":"Pressure Cooker","price":1899}- The return type is Created<ProductDto> because there is only one possible result.
- CreateProductRequest is bound automatically from the JSON body.
- TypedResults.Created(url, dto) = 201 + Location, like CreatedAtAction in controllers.
47.6 Endpoint filter: around the handler
public class TimingFilter( ILogger<TimingFilter> log) : IEndpointFilter{ public async ValueTask<object?> InvokeAsync( EndpointFilterInvocationContext ctx, EndpointFilterDelegate next) { var watch = Stopwatch.StartNew(); var result = await next(ctx); log.LogInformation("{Path} took {Ms} ms", ctx.HttpContext.Request.Path, watch.ElapsedMilliseconds); return result; }}info: TimingFilter[0] /api/products took 3 msinfo: TimingFilter[0] /api/products/1 took 2 msinfo: TimingFilter[0] /api/products/99 took 0 ms- IEndpointFilter runs code before and after the handler: like a small middleware, but only for selected endpoints or a group.
- await next(ctx) runs the rest of the filters and the handler; after it, the time is logged.
47.7 .NET 10: AddValidation
using System.ComponentModel.DataAnnotations; public record CreateProductRequest( [Required, StringLength(50)] string Name, [Range(1, 500000)] decimal Price); // Program.csbuilder.Services.AddValidation();# without AddValidation$ curl -i localhost:5047/api/products \ -H "Content-Type: application/json" \ -d '{"name":"","price":0}'HTTP/1.1 201 CreatedLocation: /api/products/3{"id":3,"name":"","price":0} # with AddValidation$ curl -i localhost:5047/api/products \ -H "Content-Type: application/json" \ -d '{"name":"","price":0}'HTTP/1.1 400 Bad RequestContent-Type: application/json; charset=utf-8{ "title": "One or more validation errors occurred.", "errors": { "Name": ["The Name field is required."], "Price": ["The field Price must be between 1 and 500000."] }}- Without AddValidation, Minimal APIs ignore DataAnnotations: an empty name gets 201 Created.
- With builder.Services.AddValidation() the same request gives 400 with a clear error per field.
- Step 1
1.Routing: group + URL + method -> endpoint
- Step 2
2.Validation: invalid body -> 400, stops here
- Step 3
3.Endpoint filters (TimingFilter) + handler run
- Step 4
4.Typed result writes status + headers + JSON
An invalid request never reaches TimingFilter, so it is not logged
47.8 Checkpoint: returning BadRequest?
static Results<Ok<ProductDto>, NotFound> GetById( int id, ProductStore store){ var product = store.Find(id); if (product is null) return TypedResults.BadRequest(); return TypedResults.Ok(product.ToDto());}$ dotnet buildProductEndpoints.cs(27,20): error CS0029: Cannot implicitly convert type 'BadRequest' to 'Results<Ok<ProductDto>, NotFound>'- The return type allows only Ok and NotFound, so the build fails with CS0029.
- The mistake is caught at compile time, long before production.
47.9 File upload: IFormFile
app.MapPost("/api/products/{id:int}/image", async (int id, IFormFile file) =>{ if (file.ContentType != "image/png") return Results.BadRequest("Only PNG"); var name = $"{id}-{Guid.NewGuid()}.png"; var path = Path.Combine("uploads", name); Directory.CreateDirectory("uploads"); await using var stream = File.Create(path); await file.CopyToAsync(stream); return Results.Ok(new { name, file.Length });}).DisableAntiforgery();$ curl -i localhost:5047/api/products/1/image \ -F "file=@notes.txt;type=text/plain"HTTP/1.1 400 Bad RequestContent-Type: application/json; charset=utf-8"Only PNG" $ curl -i localhost:5047/api/products/1/image \ -F "file=@photo.png;type=image/png"HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{"name":"1-2766d450-d344-4a54-bc19-82c89fb59fb8.png","length":21}- IFormFile receives the file from form data; check ContentType before saving.
- The server builds its own file name with a Guid.
- IFormFile endpoints expect an antiforgery token by default; without DisableAntiforgery this request fails with 500.
- DisableAntiforgery is fine for mobile apps or Postman; for browser forms add UseAntiforgery.
47.10 Comparison: Minimal APIs vs controllers
| Point | Minimal APIs | Controllers |
|---|---|---|
| Shape | Map* methods: route -> handler | Classes + action methods + attributes |
| Results | TypedResults, Results<T1, T2> | ActionResult<T>, IActionResult |
| Grouping | MapGroup + extension methods | [Route] prefix on the class |
| Cross-cutting | Endpoint filters | MVC filters |
| Validation | AddValidation (.NET 10) | [ApiController] automatic 400 |
| Choose when | New projects, less ceremony | Team uses MVC conventions, needs custom model binders / MVC filters |
47.11 Common mistakes
- Returning plain objects instead of TypedResults: null becomes 200.
- Forgetting AddValidation: DataAnnotations are silently ignored.
- Using the client's file name in a path: ../appsettings.json overwrote the server config and the app did not start on restart.
- Myth: Minimal APIs are only for demos. They are used in large production apps.
// Wrong: FileName is client inputapp.MapPost("/upload", async (IFormFile file) =>{ var path = Path.Combine("uploads", file.FileName); await using var stream = File.Create(path); await file.CopyToAsync(stream); return Results.Ok();}).DisableAntiforgery(); // curl -F "file=@notes.txt;// filename=../appsettings.json"// -> appsettings.json overwritten!Right: the server builds the name ("{id}-{Guid}.png") so the client cannot control the path.
47.12 Rules for Minimal APIs
- Return TypedResults; use Results<T1, T2> when there is more than one result.
- Organize endpoints with MapGroup + extension methods.
- Common logic (timing, logging) in endpoint filters.
- Register AddValidation in .NET 10.
- Uploads: server-made file name, never the client's.
47.13 Interview tips
- Map* methods connect a route directly to a handler; handlers return TypedResults so status and OpenAPI are correct.
- Related endpoints go in a MapGroup; cross-cutting logic in endpoint filters.
- In .NET 10 validation comes from AddValidation.
- Controllers are class based with MVC features; Minimal APIs have less ceremony and better performance.