https://codewithmukesh.com/blog/minimal-apis-aspnet-core/
What Are Minimal APIs
When to use what
Benefit
- Complex types are automatically bound from the request body, using
System.Text.Json- No need of using
[FromBody]
- No need of using
- Services registered in the DI container are automatically injected:
Route Handlers
Route handlers are the core of Minimal APIs. They define what happens when a request hits a specific URL. ASP.NET Core provides methods for all HTTP verbs:
MapGet()- Handle GET requestsMapPost()- Handle POST requestsMapPut()- Handle PUT requestsMapDelete()- Handle DELETE requestsMapPatch()- Handle PATCH requests
Parameter Biniding
Route Parameter
Route parameters are extracted from the URL path:
app.MapGet("/products/{id:int}", (int id) => /* id comes from URL */);
app.MapGet("/categories/{name}/products", (string name) => /* name from URL */);
Query Parameter
Parameters not in the route are bound from the query string:
app.MapGet("/products", (string? category, decimal? minPrice, int page = 1, int pageSize = 10) =>
{
var query = products.AsEnumerable();
if (!string.IsNullOrEmpty(category))
query = query.Where(p => p.Category == category);
if (minPrice.HasValue)
query = query.Where(p => p.Price >= minPrice);
return query.Skip((page - 1) * pageSize).Take(pageSize);
});
RouteBuilder
As your API grows, having all endpoints in Program.cs becomes unmanageable. Route groups help organize related endpoints and apply common configurations.
- This pattern keeps related endpoints together and ensures consistent URL prefixes without repetition.
- Route groups can apply common configurations to all child endpoints:
var apiGroup = app.MapGroup("/api/v1")
.RequireAuthorization();
var productsGroup = apiGroup.MapGroup("/products")
.WithTags("Products");
var categoriesGroup = apiGroup.MapGroup("/categories")
.WithTags("Categories");