wasAsked.

What is Minimal API and its use?

Impetus · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

Minimal APIs (introduced in .NET 6) let you build HTTP APIs in ASP.NET Core with very little ceremony: you map routes directly to handler functions, without controllers. Example var builder = WebApplication.CreateBuilder(args); builder.Services.AddDbContext<AppDbContext>(...); builder.Services.AddProblemDetails(); var app = builder.Build(); var products = app.MapGroup("/api/products").WithTags("Products").RequireAuthorization(); products.MapGet("/", async (AppDbContext db, CancellationToken ct) => await db.Products.AsNoTracking().ToListAsync(ct)); products.MapGet("/{id:int}", async Task<Results<Ok<Product>, NotFound>> (int id, AppDbContext db) => await db.Products.FindAsync(id) is { } p ? TypedResults.Ok(p) : TypedResults.NotFound()); products.MapPost("/", async (CreateProductRequest req, AppDbContext db) => { var product = new Product { Name = req.Name, Price = req.Price }; db.Products.Add(product); await db.SaveChangesAsync(); return TypedResults.Created($"/api/products/{product.Id}", product); }); app.Run(); Key features - Parameters are bound automatically from the route, query string, headers, body (JSON) and dependency injection services. - TypedResults and Results<...> give strongly typed responses and accurate OpenAPI metadata. - Route groups (MapGroup) share prefixes, filters, authorization, rate limiting and tags. - Endpoint filters (AddEndpointFilter) for cross-cutting logic such as validation. - Full support for authentication, authorization, OpenAPI, CORS, output caching and rate limiting. - Built-in validation support arrived in .NET 10 (AddValidation with data annotations); earlier versions used endpoint filters or FluentValidation. - Native AOT compatibility with the request delegate generator, for fast startup and small footprints. Uses and benefits - Microservices and small focused APIs with less boilerplate. - High-performance endpoints (slightly less overhead than MVC). - Serverless or container workloads where startup time matters. - Prototypes and learning. When controllers may still fit better - Large APIs where teams prefer the familiar controller structure and MVC conventions. - Features that rely on MVC-specific capabilities (some filter types, model binding customisations, conventions). Large minimal API projects stay organised by grouping endpoints into feature files with extension methods (for example app.MapOrderEndpoints()) or by using libraries like Carter or FastEndpoints. Both approaches run on the same ASP.NET Core pipeline and can coexist in one application.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics