Minimal APIs
MapGet/Post, route groups and endpoint filters.
Minimal APIs in ASP.NET Core
Category: ASP.NET Core Fundamentals
Difficulty: Intermediate
Target framework: .NET 9+
Previous topic: Razor Pages
Topic focus:MapGet,MapPost, route groups, and endpoint filters
1. About
Build concise, production-minded HTTP APIs using Minimal APIs, route groups, dependency injection, validation, and endpoint filters.
Prerequisites
- Basic C# and object-oriented programming
- HTTP methods, status codes, and JSON
- ASP.NET Core middleware and dependency injection
- Basic routing and asynchronous programming
- Familiarity with MVC and Razor Pages
Learning outcomes
By the end of this module, you will be able to:
- Explain what Minimal APIs are and when to use them.
- Map endpoints with
MapGet,MapPost,MapPut,MapPatch, andMapDelete. - Understand route templates, parameter binding, and endpoint metadata.
- Group related endpoints with
MapGroup. - Apply endpoint filters to validate or inspect endpoint calls.
- Register services and use DI in endpoint handlers.
- Return appropriate HTTP status codes and typed results.
- Design safer, testable, and maintainable APIs.
- Compare Minimal APIs with controller-based Web APIs.
2. Introduction
What are Minimal APIs?
Minimal APIs are an ASP.NET Core programming model for building HTTP APIs with a small amount of ceremony. Instead of requiring a controller class for every set of endpoints, you can map a URL and HTTP method directly to a handler.
For example:
app.MapGet("/hello", () => "Hello, API!");
This maps a GET request to /hello to a handler that returns a response. ASP.NET Core serializes supported return values as appropriate for the endpoint.
Minimal APIs are not a separate web server or a replacement for ASP.NET Core. They use the same core HTTP pipeline, routing, dependency injection, configuration, logging, authentication, and authorization infrastructure.
Why do Minimal APIs exist?
Some APIs have a small set of straightforward endpoints. Requiring a controller, action method, and related scaffolding for every small endpoint can add structure without always adding value.
Minimal APIs provide:
- Direct endpoint definitions.
- Less ceremony for small services and focused APIs.
- Built-in support for dependency injection and parameter binding.
- Route groups for shared configuration.
- Endpoint filters for endpoint-level cross-cutting logic.
- Strong integration with OpenAPI tooling when configured.
Important: “Minimal” describes the programming model, not the quality bar. Production APIs still need validation, authorization, observability, error handling, testing, and thoughtful organization.
3. Real-life analogy: A parcel service counter
Imagine a parcel service with several counters:
- One counter checks a parcel's tracking status.
- Another accepts a new parcel booking.
- Another updates delivery instructions.
- Another cancels a booking.
Each counter is a specific operation, and each operation accepts particular information and returns a result. A common front desk may apply shared rules such as checking identification or recording the visit.
In a Minimal API:
- The URL and HTTP method identify the operation.
- A handler executes the endpoint's work.
- Dependency injection supplies shared services.
- A route group can apply shared conventions to related endpoints.
- An endpoint filter can inspect arguments or results around handler execution.
The analogy is useful because it emphasizes clear, purpose-specific endpoints without requiring every endpoint to have its own controller class.
4. Architecture diagram
Endpoint filters wrap endpoint handler execution. Middleware runs in the broader HTTP pipeline. Both can provide cross-cutting behavior, but they operate at different levels and have different access to endpoint arguments and results.
5. Concept explanation
5.1 What is an endpoint?
An endpoint is a configured target that can handle a matching HTTP request. It typically has:
- A route pattern.
- HTTP method or other matching metadata.
- A handler.
- Optional metadata, authorization requirements, filters, and other conventions.
Example:
app.MapGet("/products", () => Results.Ok(new[] { "Keyboard", "Mouse" }));
This maps the GET method and /products route to a handler that returns an HTTP 200 response containing data.
5.2 MapGet
MapGet maps a handler for HTTP GET requests.
app.MapGet("/health", () => Results.Ok(new { status = "healthy" }));
GET is commonly used to retrieve information. A GET endpoint should not perform a state-changing operation as a side effect.
5.3 MapPost
MapPost maps a handler for HTTP POST requests. POST is commonly used to submit data or initiate an operation.
app.MapPost("/echo", (EchoRequest request) =>
Results.Ok(new { received = request.Message }));
public sealed record EchoRequest(string Message);
The request body is typically JSON when the client sends a JSON payload and the handler accepts a complex body-bound type.
For example:
POST /echo
Content-Type: application/json
{
"message": "Hello"
}
The exact body-binding behavior depends on the handler signature, route and query parameters, service registrations, and request content type.
5.4 Other HTTP method mappings
| Method | Common purpose | Mapping |
|---|---|---|
| GET | Retrieve information | MapGet |
| POST | Create or initiate an operation | MapPost |
| PUT | Replace/update a resource representation | MapPut |
| PATCH | Partially update a resource | MapPatch |
| DELETE | Delete a resource | MapDelete |
These are conventions, not complete business rules. Design each endpoint to use HTTP methods consistently and document its behavior.
5.5 Route templates and parameters
A route template describes the URL shape an endpoint matches.
app.MapGet("/products/{id:int}", (int id) =>
Results.Ok(new { ProductId = id }));
For /products/12, the handler can receive id = 12.
{id}defines a route parameter.:intis a route constraint.- The handler's
int idparameter receives the bound value.
Route constraints help select matching endpoints. They do not prove that the product exists or that the caller is authorized to access it.
Query-string example:
app.MapGet("/products/search", (string? term) =>
Results.Ok(new { SearchTerm = term }));
A request such as /products/search?term=keyboard can bind the query value to term.
5.6 Parameter binding
Minimal APIs can bind handler parameters from supported sources, including:
- Route values.
- Query strings.
- HTTP headers.
- JSON request bodies.
- Dependency injection services.
- Special request abstractions such as
HttpContextandCancellationToken.
Binding source inference depends on the parameter type, route configuration, and registered services. For clarity, use explicit binding attributes such as [FromRoute], [FromQuery], [FromHeader], [FromBody], and [FromServices] when useful.
using Microsoft.AspNetCore.Mvc;
app.MapGet("/products/{id:int}", ([FromRoute] int id,
[FromQuery] bool includeDetails) =>
{
return Results.Ok(new { id, includeDetails });
});
5.7 Returning results and status codes
Minimal APIs support IResult implementations through the Results and TypedResults helpers.
| Helper | Typical meaning | Example |
|---|---|---|
Results.Ok(data) | HTTP 200 | Successful retrieval |
Results.Created(uri, data) | HTTP 201 | Resource created |
Results.NoContent() | HTTP 204 | Successful operation with no response body |
Results.BadRequest() | HTTP 400 | Invalid request |
Results.NotFound() | HTTP 404 | Resource not found |
Results.Unauthorized() | HTTP 401 | Authentication required/failed |
Results.Forbid() | HTTP 403 | Caller is not permitted |
Results.Conflict() | HTTP 409 | Conflict with current state |
Choose status codes according to the endpoint's semantics. Do not return HTTP 200 for every outcome.
5.8 Dependency injection in handlers
Minimal API handlers can receive registered services as parameters.
app.MapGet("/time", (TimeProvider timeProvider) =>
Results.Ok(new { utcNow = timeProvider.GetUtcNow() }));
Register TimeProvider:
builder.Services.AddSingleton(TimeProvider.System);
For application services:
builder.Services.AddScoped<IProductService, ProductService>();
app.MapGet("/products", async (
IProductService products,
CancellationToken cancellationToken) =>
{
var items = await products.GetAllAsync(cancellationToken);
return Results.Ok(items);
});
DI keeps endpoint handlers focused on HTTP behavior and makes services easier to replace in tests.
5.9 Route groups with MapGroup
Route groups organize related endpoints under a shared prefix and allow shared configuration.
var products = app.MapGroup("/api/products");
products.MapGet("/", () => Results.Ok("List products"));
products.MapGet("/{id:int}", (int id) => Results.Ok(new { id }));
products.MapPost("/", () => Results.Created("/api/products/1", new { id = 1 }));
The shared prefix is /api/products, so the endpoints become:
GET /api/products/GET /api/products/{id}POST /api/products/
A route group can also share authorization requirements, tags, filters, and other endpoint conventions.
var admin = app.MapGroup("/api/admin")
.RequireAuthorization();
admin.MapGet("/reports", () => Results.Ok("Protected report"));
This requires authorization according to the application's configured authentication and authorization services and policies.
5.10 Endpoint filters
An endpoint filter can run logic before and after a Minimal API handler. Filters are useful for concerns closely related to endpoint invocation, such as checking arguments or logging selected endpoint activity.
An endpoint filter implements IEndpointFilter:
using Microsoft.AspNetCore.Http;
public sealed class RequireProductNameFilter : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context,
EndpointFilterDelegate next)
{
var request = context.Arguments
.OfType<CreateProductRequest>()
.FirstOrDefault();
if (request is null || string.IsNullOrWhiteSpace(request.Name))
{
return Results.ValidationProblem(
new Dictionary<string, string[]>
{
["name"] = ["Product name is required."]
});
}
return await next(context);
}
}
Attach it to an endpoint:
app.MapPost("/products", (CreateProductRequest request) =>
{
return Results.Created("/products/1", new { request.Name });
})
.AddEndpointFilter<RequireProductNameFilter>();
Register the filter if it uses constructor-injected dependencies:
builder.Services.AddScoped<RequireProductNameFilter>();
Filters can also be added to route groups, allowing shared behavior across endpoints in that group.
Design note: Endpoint filters are not a replacement for domain validation or authorization. Use validation rules in the appropriate application/domain layer as well, especially when the same operation is called from multiple endpoints.
5.11 Endpoint filters vs middleware
| Aspect | Middleware | Endpoint filter |
|---|---|---|
| Scope | HTTP pipeline, potentially all requests | Minimal API endpoint invocation |
| Access to handler arguments | Usually no direct typed handler-argument access | Yes, through invocation context |
| Typical use | Exception handling, request logging, authentication pipeline | Endpoint-specific validation, argument inspection, handler/result wrapping |
| Placement | Configured in middleware pipeline | Attached to endpoint or route group |
| Runs for static files/non-endpoint requests? | Can, depending on placement | Only when a matching filtered endpoint executes |
5.12 Validation and error handling
Minimal APIs support model binding and validation capabilities that vary by framework version and configuration. For portable, explicit behavior, validate request models and return a suitable response when invalid. In .NET 9, do not assume every validation attribute automatically produces the same behavior as an MVC controller decorated with [ApiController]; design and test the validation flow you need.
Example:
using System.ComponentModel.DataAnnotations;
public sealed record CreateProductRequest(
[property: Required, StringLength(100, MinimumLength = 2)]
string Name,
[property: Range(typeof(decimal), "0.01", "1000000")]
decimal Price);
A production endpoint should validate the request before invoking the application service. The service/domain layer should also enforce business rules that matter regardless of how it is called.
5.13 OpenAPI and API documentation
OpenAPI describes API routes, parameters, request bodies, and responses in a machine-readable format. ASP.NET Core supports OpenAPI document generation with appropriate services and endpoint mapping.
For a .NET 9 application, a typical setup is:
builder.Services.AddOpenApi();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
This snippet illustrates registration and mapping only. Follow the application's API documentation and deployment requirements when deciding whether to expose the document outside development. A UI such as Swagger UI may require an additional package.
6. Important terminology
| Term | Meaning | Example |
|---|---|---|
| Minimal API | ASP.NET Core model for mapping HTTP handlers with minimal ceremony | app.MapGet(...) |
| Endpoint | Configured target for a matching request | GET /products |
| Handler | Delegate that processes an endpoint request | (int id) => ... |
| Route template | Pattern describing a URL | /products/{id:int} |
| Route constraint | Restricts route matching | {id:int} |
| Parameter binding | Supplies route/query/body/service values to a handler | int id |
MapGet | Maps a GET handler | app.MapGet("/health", ...) |
MapPost | Maps a POST handler | app.MapPost("/products", ...) |
MapGroup | Groups endpoints under a common prefix/convention | app.MapGroup("/api/products") |
| Endpoint filter | Wraps endpoint handler execution | AddEndpointFilter<T>() |
| Middleware | Component in the HTTP pipeline | app.UseAuthentication() |
IResult | Abstraction for an HTTP result | Results.NotFound() |
| DI | Supplies dependencies to handlers | IProductService |
| OpenAPI | Machine-readable API description format | API document |
7. How it works internally
A typical Minimal API request follows these steps:
- The client sends an HTTP request.
- Middleware processes the request in configured order.
- Endpoint routing matches the route and HTTP method.
- Endpoint metadata and applicable authorization rules are evaluated through the configured pipeline.
- Minimal API binding obtains values from route, query, body, headers, or DI.
- Applicable endpoint filters execute around handler invocation.
- The handler calls application services or performs a small operation.
- The handler returns an HTTP result.
- ASP.NET Core writes the response and continues through the remaining middleware.
This is a simplified conceptual flow. Actual middleware, authorization, binding, filter, and result execution stages depend on endpoint configuration.
8. Syntax explained
MapGet
app.MapGet("/products/{id:int}", (int id) =>
Results.Ok(new { id }));
app: the configuredWebApplication.MapGet: maps an endpoint for HTTP GET."/products/{id:int}": route template with an integer parameter.(int id) =>: handler delegate whose parameter is bound from the request.Results.Ok(...): produces an HTTP 200 result containing the supplied data.
MapPost
app.MapPost("/products", (CreateProductRequest request) =>
Results.Created("/products/1", request));
MapPost: maps an endpoint for HTTP POST.request: complex request data, commonly bound from a JSON body.Results.Created: returns HTTP 201 with a location and response value.
In a real create operation, use the ID returned by persistence rather than hardcoding the location.
MapGroup
var api = app.MapGroup("/api/products");
api.MapGet("/", GetProducts);
The group provides a common route prefix and a place to apply shared endpoint conventions. Grouping can reduce repeated configuration and clarify the API's structure.
AddEndpointFilter
endpoint.AddEndpointFilter<MyFilter>();
Adds an endpoint filter to the selected endpoint builder. A filter receives the endpoint invocation context and a delegate that continues to the next filter or handler.
9. Code examples
9.1 Simple example: GET and POST
Program.cs:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// GET: retrieve a simple message.
app.MapGet("/hello", () => Results.Ok(new
{
message = "Hello from a Minimal API!"
}));
// POST: accept a request body and return it.
app.MapPost("/echo", (EchoRequest request) =>
{
return Results.Ok(new { received = request.Message });
});
app.Run();
public sealed record EchoRequest(string Message);
Test the GET endpoint:
GET /hello
Example response:
{
"message": "Hello from a Minimal API!"
}
Test the POST endpoint with a JSON body:
POST /echo
Content-Type: application/json
{
"message": "Hello"
}
Example response:
{
"received": "Hello"
}
The echo endpoint is a learning example. Production endpoints should define validation, limits, authorization where needed, and appropriate error handling.
9.2 Intermediate example: Route groups and CRUD-style endpoints
This example uses an in-memory collection to illustrate route design. In-memory data resets when the application restarts and is not appropriate as shared production persistence.
Program.cs:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var products = new List<Product>
{
new(1, "Keyboard", 2499m),
new(2, "Mouse", 799m)
};
var nextId = 3;
var productRoutes = app.MapGroup("/api/products")
.WithTags("Products");
// GET /api/products
productRoutes.MapGet("/", () => Results.Ok(products));
// GET /api/products/1
productRoutes.MapGet("/{id:int}", (int id) =>
{
var product = products.FirstOrDefault(p => p.Id == id);
return product is null
? Results.NotFound()
: Results.Ok(product);
});
// POST /api/products
productRoutes.MapPost("/", (CreateProductRequest request) =>
{
if (string.IsNullOrWhiteSpace(request.Name) ||
request.Name.Length > 100 ||
request.Price <= 0)
{
return Results.BadRequest(new
{
error = "A name of 1-100 characters and a positive price are required."
});
}
var product = new Product(nextId++, request.Name.Trim(), request.Price);
products.Add(product);
return Results.Created($"/api/products/{product.Id}", product);
});
// DELETE /api/products/1
productRoutes.MapDelete("/{id:int}", (int id) =>
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product is null)
{
return Results.NotFound();
}
products.Remove(product);
return Results.NoContent();
});
app.Run();
public sealed record Product(int Id, string Name, decimal Price);
public sealed record CreateProductRequest(string Name, decimal Price);
Important limitations: This example does not provide thread-safe persistence, database transactions, authentication, authorization, or comprehensive validation. Do not use this mutable in-memory collection as a production data store. The sample uses a simple validation check to make the flow explicit; a real application should use a suitable validation strategy and enforce business rules in its application/domain layer.
9.3 Production example: Service-based endpoint with a filter
This example illustrates a cleaner structure with DI, async I/O, typed results, route groups, and an endpoint filter. The data service implementation is shown with EF Core so the endpoint itself remains focused on HTTP concerns.
Entity and DbContext
Data/ProductEntity.cs:
namespace MinimalApiDemo.Data;
public sealed class ProductEntity
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
Data/AppDbContext.cs:
using Microsoft.EntityFrameworkCore;
namespace MinimalApiDemo.Data;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
: DbContext(options)
{
public DbSet<ProductEntity> Products => Set<ProductEntity>();
}
Request and response models
Models/CreateProductRequest.cs:
using System.ComponentModel.DataAnnotations;
namespace MinimalApiDemo.Models;
public sealed record CreateProductRequest(
[property: Required, StringLength(100, MinimumLength = 2)]
string Name,
[property: Range(typeof(decimal), "0.01", "1000000")]
decimal Price);
Models/ProductResponse.cs:
namespace MinimalApiDemo.Models;
public sealed record ProductResponse(int Id, string Name, decimal Price);
Service contract
Services/IProductService.cs:
using MinimalApiDemo.Models;
namespace MinimalApiDemo.Services;
public interface IProductService
{
Task<IReadOnlyList<ProductResponse>> GetAllAsync(
CancellationToken cancellationToken);
Task<ProductResponse?> GetByIdAsync(
int id,
CancellationToken cancellationToken);
Task<ProductResponse> CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken);
}
Service implementation
Services/ProductService.cs:
using Microsoft.EntityFrameworkCore;
using MinimalApiDemo.Data;
using MinimalApiDemo.Models;
namespace MinimalApiDemo.Services;
public sealed class ProductService(AppDbContext db) : IProductService
{
public async Task<IReadOnlyList<ProductResponse>> GetAllAsync(
CancellationToken cancellationToken)
{
return await db.Products
.AsNoTracking()
.OrderBy(p => p.Name)
.Select(p => new ProductResponse(p.Id, p.Name, p.Price))
.ToListAsync(cancellationToken);
}
public async Task<ProductResponse?> GetByIdAsync(
int id,
CancellationToken cancellationToken)
{
return await db.Products
.AsNoTracking()
.Where(p => p.Id == id)
.Select(p => new ProductResponse(p.Id, p.Name, p.Price))
.SingleOrDefaultAsync(cancellationToken);
}
public async Task<ProductResponse> CreateAsync(
CreateProductRequest request,
CancellationToken cancellationToken)
{
var entity = new ProductEntity
{
Name = request.Name.Trim(),
Price = request.Price
};
db.Products.Add(entity);
await db.SaveChangesAsync(cancellationToken);
return new ProductResponse(entity.Id, entity.Name, entity.Price);
}
}
Endpoint filter
Filters/ProductRequestFilter.cs:
using MinimalApiDemo.Models;
namespace MinimalApiDemo.Filters;
public sealed class ProductRequestFilter : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(
EndpointFilterInvocationContext context,
EndpointFilterDelegate next)
{
var request = context.Arguments
.OfType<CreateProductRequest>()
.FirstOrDefault();
if (request is null ||
string.IsNullOrWhiteSpace(request.Name) ||
request.Name.Trim().Length < 2 ||
request.Name.Trim().Length > 100 ||
request.Price <= 0)
{
return Results.ValidationProblem(
new Dictionary<string, string[]>
{
["request"] =
[
"Provide a product name of 2-100 characters and a positive price."
]
});
}
return await next(context);
}
}
The filter demonstrates endpoint-level validation for this request type. Keep authoritative business rules in the service/domain layer too, particularly when the same operation can be called from other entry points.
Program.cs
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using MinimalApiDemo.Data;
using MinimalApiDemo.Filters;
using MinimalApiDemo.Models;
using MinimalApiDemo.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<ProductRequestFilter>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler();
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
var products = app.MapGroup("/api/products")
.WithTags("Products");
// Read all products.
products.MapGet("/", async (
IProductService service,
CancellationToken cancellationToken) =>
{
var result = await service.GetAllAsync(cancellationToken);
return TypedResults.Ok(result);
})
.Produces<IReadOnlyList<ProductResponse>>(StatusCodes.Status200OK);
// Read one product.
products.MapGet("/{id:int}", async Task<Results<Ok<ProductResponse>, NotFound>> (
int id,
IProductService service,
CancellationToken cancellationToken) =>
{
var product = await service.GetByIdAsync(id, cancellationToken);
return product is null
? TypedResults.NotFound()
: TypedResults.Ok(product);
});
// Create a product.
products.MapPost("/", async Task<Results<Created<ProductResponse>, ValidationProblem>> (
CreateProductRequest request,
IProductService service,
CancellationToken cancellationToken) =>
{
var product = await service.CreateAsync(request, cancellationToken);
return TypedResults.Created($"/api/products/{product.Id}", product);
})
.AddEndpointFilter<ProductRequestFilter>()
.ProducesValidationProblem();
app.Run();
This sample demonstrates typed results, OpenAPI generation, route grouping, DI, asynchronous persistence, and an endpoint filter. Review and adjust exception handling for your application's target framework and desired error response behavior. In particular, ensure the production exception handler is configured with the appropriate error endpoint or response policy for your application.
Configuration: Supply DefaultConnection through user secrets or secure deployment configuration. Do not commit production credentials. Set up and apply EF Core migrations as part of the database deployment workflow.
Production additions: This is a teaching foundation, not a complete production API. Add authentication and endpoint authorization policies as required, paging and query limits for collection endpoints, rate limiting where appropriate, database constraints, comprehensive validation, monitoring, integration tests, and a consistent error contract.
10. Recommended folder structure
MinimalApiDemo/
├── Data/
│ ├── AppDbContext.cs
│ └── ProductEntity.cs
├── Filters/
│ └── ProductRequestFilter.cs
├── Models/
│ ├── CreateProductRequest.cs
│ └── ProductResponse.cs
├── Services/
│ ├── IProductService.cs
│ └── ProductService.cs
├── Endpoints/
│ └── ProductEndpoints.cs
├── Program.cs
├── appsettings.json
└── MinimalApiDemo.csproj
For a growing API, move endpoint registration into extension methods or endpoint-mapping classes. For example, ProductEndpoints.MapProductEndpoints(IEndpointRouteBuilder app) can register product routes. Keep route registration discoverable and avoid a single enormous Program.cs.
11. Execution flow: line by line
Consider this endpoint:
products.MapGet("/{id:int}", async (
int id,
IProductService service,
CancellationToken cancellationToken) =>
{
var product = await service.GetByIdAsync(id, cancellationToken);
return product is null
? TypedResults.NotFound()
: TypedResults.Ok(product);
});
- The application registers this handler during startup.
- A client sends
GET /api/products/12. - Middleware processes the request.
- Routing matches the
/api/productsgroup plus the/{id:int}route. - ASP.NET Core binds
12toid. - DI supplies
IProductService. - The request cancellation token is passed to the handler.
- The handler calls the service.
- The service queries the database asynchronously.
- If the product is missing, the handler returns HTTP 404.
- If the product exists, the handler returns HTTP 200 with the response model.
- ASP.NET Core serializes the response and sends it to the client.
12. Real project usage
| Industry | Example | Minimal API role |
|---|---|---|
| E-commerce | Product catalog, cart operations | Endpoints for retrieving products and submitting cart actions |
| Banking | Account summary service | Protected endpoints with strict authorization and audit controls |
| Healthcare | Appointment availability API | Search and booking endpoints with careful validation and privacy controls |
| Logistics | Shipment tracking API | Route-based retrieval of tracking status |
| Social media | Feed or profile APIs | Data endpoints for web and mobile clients |
| Enterprise software | Internal integration services | Focused endpoints that expose well-defined application operations |
Minimal APIs are especially useful for focused HTTP services, but endpoint count alone should not determine architecture. Large APIs still need modular registration, application services, policies, testing, and clear contracts.
13. Performance considerations
Memory
- Return bounded collections and paginate large results.
- Project database rows to response DTOs instead of materializing entire entities unnecessarily.
- Avoid unbounded request bodies and uncontrolled buffering.
- Do not store request-specific state in singleton services.
CPU
- Keep endpoint handlers small.
- Avoid expensive synchronous work on request threads.
- Profile serialization, mapping, and business computations before optimizing.
- Use efficient query shapes and avoid repeated transformations.
Scalability
- Use asynchronous I/O for databases and downstream services.
- Pass cancellation tokens to supported operations.
- Configure timeouts and connection pooling appropriately.
- Keep services stateless where possible and use shared persistence for state that must survive across instances.
Optimization
- Use database indexes based on observed query patterns.
- Add pagination, filtering, and query limits.
- Cache only when freshness and authorization rules allow it.
- Use response compression and HTTP caching when appropriate.
- Measure latency, throughput, database time, memory, and errors.
Note: Minimal APIs reduce some framework ceremony; they do not automatically make database access, serialization, or business logic faster. Performance depends on the whole request path.
14. Security considerations
Authentication and authorization
Require authentication and authorization for protected endpoints.
var accountRoutes = app.MapGroup("/api/account")
.RequireAuthorization();
Authentication identifies the caller; authorization determines what that caller is allowed to do. Resource-level checks are still needed for data such as a particular account or order.
Input validation
Treat request bodies, route parameters, headers, and query values as untrusted.
Defense: Validate shape and constraints at the API boundary and enforce business rules in the application/domain layer.
Mass assignment / overposting
Binding persistence entities directly can expose fields that callers should not control.
Defense: Use request DTOs with only the allowed fields and map them explicitly.
SQL injection
Concatenating untrusted input into SQL can alter query behavior.
Defense: Use EF Core LINQ or parameterized SQL.
Cross-site request forgery
CSRF risk depends on the authentication mechanism and how the API is called. Cookie-authenticated endpoints that perform state changes need appropriate CSRF defenses. APIs using bearer tokens in the Authorization header have a different threat profile, but still require careful token storage and validation.
Sensitive data exposure
Do not return internal entities or exception details blindly.
Defense: Use response DTOs, safe error responses, HTTPS, secure configuration, and structured logs that avoid secrets.
Rate limiting and resource exhaustion
Public endpoints can be abused with large payloads, expensive queries, or high request rates.
Defense: Configure request limits, rate limiting where appropriate, pagination, timeouts, and resource quotas.
Additional practices
- Keep production secrets out of source control.
- Use least-privilege database credentials.
- Apply authentication and authorization policies consistently.
- Validate uploaded files if supported.
- Keep dependencies patched.
- Avoid logging credentials, tokens, or sensitive request bodies.
- Return accurate status codes without leaking private information.
15. Ten common mistakes
| # | Mistake | Why it happens | How to fix it |
|---|---|---|---|
| 1 | Putting every endpoint in Program.cs | Minimal examples start there | Extract endpoint registration by feature as the API grows |
| 2 | Returning HTTP 200 for every outcome | Status codes are overlooked | Use accurate status codes and result types |
| 3 | Accepting persistence entities as request bodies | It reduces initial typing | Use narrow request DTOs |
| 4 | Skipping server-side validation | The request appears well-formed | Validate input and enforce domain rules |
| 5 | Confusing route constraints with validation | {id:int} looks restrictive | Check resource existence, validity, and authorization separately |
| 6 | Forgetting authorization on a route group | Shared routes seem internal | Apply policies deliberately and test protected endpoints |
| 7 | Doing database work inside filters | Filters seem convenient for all logic | Keep filters focused and delegate use cases to services |
| 8 | Returning unbounded lists | Small test datasets hide costs | Add pagination, filtering, and query limits |
| 9 | Using mutable static/in-memory collections as production storage | They make demos easy | Use durable, concurrency-safe persistence |
| 10 | Assuming Minimal APIs are automatically faster | The name suggests performance | Measure the whole request path and optimize real bottlenecks |
16. Production best practices
- Keep handlers focused. Delegate substantial use cases to application services.
- Organize endpoints by feature. Move route registration into extension methods when
Program.csbecomes difficult to navigate. - Use route groups. Share prefixes, tags, authorization requirements, and filters where appropriate.
- Use explicit request and response DTOs. Avoid exposing persistence entities indiscriminately.
- Return correct status codes. Use 201 for successful creation where appropriate, 404 for missing resources, and meaningful validation responses.
- Validate input at the boundary. Enforce business invariants in the application/domain layer too.
- Use dependency injection. Avoid manually creating infrastructure dependencies inside handlers.
- Use asynchronous I/O. Prefer asynchronous database and network APIs.
- Propagate cancellation tokens. Let downstream operations observe cancellation.
- Apply authorization consistently. Use policies and resource-level checks.
- Protect sensitive state-changing operations. Consider the authentication mechanism and CSRF threat model.
- Use parameterized data access. Do not concatenate untrusted strings into SQL.
- Paginate large collections. Avoid returning entire tables.
- Use projection. Retrieve only the fields the client needs.
- Configure centralized error handling. Return safe errors and log diagnostics securely.
- Use structured logging. Record useful context without secrets or sensitive payloads.
- Document endpoints with OpenAPI. Keep descriptions, response types, and route metadata accurate.
- Use typed results where helpful. They make expected response types clearer and can improve API metadata.
- Add endpoint filters selectively. Use them for cross-cutting endpoint invocation concerns, not as a replacement for domain rules.
- Distinguish middleware from filters. Put behavior at the layer with the correct scope.
- Configure rate limiting where appropriate. Protect expensive or public endpoints from abuse.
- Set timeouts and request-size limits. Avoid unbounded work and payloads.
- Keep service lifetimes correct. Do not capture scoped services in singletons.
- Test endpoint behavior. Include binding, validation, authorization, status codes, and persistence.
- Use integration tests. Verify the real HTTP pipeline rather than testing only handler delegates.
- Avoid accidental data leaks. Return response models rather than internal entities or exception details.
- Keep configuration secure. Use user secrets locally and secure deployment configuration.
- Review API versioning and compatibility. Avoid silently breaking clients when contracts change.
- Measure before optimizing. Profile serialization, database queries, and downstream calls.
- Keep endpoints predictable. Use consistent naming, HTTP method semantics, and error response shapes.
17. Interview questions
Beginner questions
1. What are Minimal APIs?
Minimal APIs are an ASP.NET Core programming model for defining HTTP endpoints with concise handler mappings rather than requiring controller classes for every endpoint.
2. What does MapGet do?
It maps a handler to a route for HTTP GET requests. GET is generally used to retrieve information without changing server state.
3. What does MapPost do?
It maps a handler to a route for HTTP POST requests. POST commonly accepts submitted data or initiates an operation.
4. What is a route template?
A route template describes the URL pattern an endpoint matches, such as /products/{id:int}.
5. What is a route group?
A route group created by MapGroup organizes related endpoints under a common prefix and lets them share endpoint conventions such as authorization, tags, or filters.
6. What is an endpoint filter?
An endpoint filter wraps a Minimal API handler and can inspect arguments, run logic before the handler, and inspect or replace the result afterward.
7. Can Minimal API handlers use dependency injection?
Yes. Registered services can be declared as handler parameters and are resolved through the built-in DI container.
8. What is the purpose of Results.NotFound()?
It returns an HTTP 404 response, typically when the requested resource cannot be found.
9. How do you map a route parameter?
Define it in the route template, such as /{id:int}, and accept a compatible handler parameter such as int id.
10. Are Minimal APIs only for tiny applications?
No. They can support large APIs when endpoints are organized into modules and backed by maintainable application services, security policies, and tests.
Intermediate questions
11. What is the difference between Results and TypedResults?
Both provide helpers for producing HTTP results. TypedResults returns concrete typed result objects, which can make response types clearer to the compiler and improve endpoint metadata. Results offers convenient result helpers with less emphasis on concrete result types.
12. How does parameter binding work in Minimal APIs?
ASP.NET Core binds handler parameters from supported sources such as route values, query strings, headers, request bodies, and DI services. Inference depends on parameter types and endpoint configuration; binding attributes can clarify the intended source.
13. What is the difference between middleware and endpoint filters?
Middleware operates in the broader HTTP pipeline and can apply to many kinds of requests. Endpoint filters wrap Minimal API handler invocation and can access handler arguments and results.
14. How do you secure a route group?
Use RequireAuthorization() or a specific authorization policy on the group, and ensure authentication and authorization services and middleware are configured. Add resource-level authorization where required.
15. Why use DTOs?
DTOs define the API's accepted and returned data shape. They avoid exposing internal entities, reduce overposting risks, and make API contracts more stable.
16. How would you handle invalid request input?
Validate the request, return a clear 400 or validation-problem response, and ensure business rules are also enforced by the application/domain layer.
17. Why use CancellationToken in a handler?
It allows the handler and supported downstream operations to observe request cancellation, potentially avoiding unnecessary database or network work.
18. How do you document Minimal APIs?
Configure OpenAPI generation and map the OpenAPI endpoint as appropriate. Add endpoint metadata, descriptions, tags, and accurate response declarations. A documentation UI may require an additional package.
19. Why use route groups?
Groups reduce repeated route prefixes and shared endpoint configuration. They can also apply authorization, tags, and filters consistently to related endpoints.
20. Are endpoint filters a good place for business logic?
Usually not for core business rules. Filters suit endpoint-level cross-cutting behavior; domain and application rules should live in components that remain valid regardless of the calling endpoint.
Advanced questions
21. When would you choose Minimal APIs over controller-based APIs?
Choose Minimal APIs when direct endpoint mapping and low ceremony fit the service. Controllers may be useful when controller/action organization, MVC conventions, filters, or established team patterns make the application easier to maintain. Both are capable ASP.NET Core API models.
22. How do you prevent overposting?
Use dedicated request DTOs containing only allowed fields, validate them, authorize the operation, and explicitly map permitted values to domain or persistence models.
23. How do route constraints differ from validation?
Constraints help determine whether a URL matches an endpoint. Validation checks whether bound data is acceptable. Neither proves that a resource exists or that a caller is authorized to access it.
24. How would you implement consistent error handling?
Configure centralized exception handling and define a consistent error contract, such as problem details. Log diagnostic information securely and avoid returning exception internals to clients.
25. How would you improve a slow Minimal API endpoint?
Measure endpoint latency, database duration, and downstream calls. Inspect query plans, project only required fields, paginate results, use asynchronous I/O, and cache only when freshness and authorization rules allow it.
26. What are the risks of using a static in-memory list?
It is not durable, can be inconsistent across application instances, may have concurrency problems, and loses data on restart. Use a suitable persistent store for production data.
27. How do typed results help?
They make possible response types explicit in handler signatures and can improve compiler checking and endpoint metadata. They are particularly useful when an endpoint has a small, known set of response outcomes.
28. How do you test Minimal APIs?
Use unit tests for application services and domain behavior, and integration tests with an in-memory test server or test host to verify routing, binding, filters, authorization, status codes, and persistence.
29. How should filters and authorization interact?
Authorization should be configured through ASP.NET Core's authentication and authorization mechanisms and policies. Do not use a custom endpoint filter as a substitute for the framework's authorization system.
30. What should you consider when grouping endpoints?
Use groups that reflect a clear feature or resource area. Apply shared conventions deliberately, avoid assuming a route prefix alone provides security, and test that inherited metadata and filters behave as intended.
18. Hands-on exercise
Exercise: Build a task-tracking API
Goal: Create a small Minimal API for managing tasks.
Requirements
- Create a
TaskItemresponse model and aCreateTaskRequestinput model. - Implement
GET /api/tasksto list tasks. - Implement
GET /api/tasks/{id:int}to retrieve one task. - Implement
POST /api/tasksto create a task. - Implement
PUT /api/tasks/{id:int}to update a task. - Implement
DELETE /api/tasks/{id:int}to delete a task. - Group endpoints using
MapGroup("/api/tasks"). - Validate input and return appropriate status codes.
- Add an endpoint filter that checks a cross-cutting request requirement.
- Add tests for successful, invalid, and missing-resource cases.
Acceptance criteria
- Routes use consistent HTTP method semantics.
- Missing resources return 404.
- Invalid requests return a clear 400/validation response.
- Creation returns 201 with a resource location.
- Handlers remain focused and call a service.
- The API is tested through HTTP integration tests.
Extension: Replace in-memory data with EF Core and add pagination, OpenAPI documentation, and authorization.
19. Mini project: Product catalog API
Project goal
Build a product catalog API using Minimal APIs, route groups, endpoint filters, EF Core, and a service layer.
Features
- List and search products
- Retrieve product details
- Create, update, and delete products
- Request and response DTOs
- Input validation and consistent error responses
- EF Core persistence
- Route groups and shared metadata
- Endpoint filters for a suitable cross-cutting concern
- Authentication and authorization where needed
- OpenAPI documentation
- Logging, exception handling, and automated tests
Suggested milestones
| Milestone | Deliverable |
|---|---|
| 1. Endpoint setup | Map GET and POST endpoints |
| 2. Route design | Group routes by product resource |
| 3. Application layer | Add service interface and implementation |
| 4. Persistence | Add EF Core context and migrations |
| 5. Validation | Add request DTOs and validation behavior |
| 6. Cross-cutting behavior | Add an endpoint filter and appropriate policies |
| 7. Documentation | Add OpenAPI descriptions and response metadata |
| 8. Quality | Add integration tests, logging, and error handling |
Definition of done
Clients can perform the documented product operations, invalid requests are rejected, protected operations require appropriate permissions, errors have consistent responses, and critical endpoints are covered by integration tests.
20. Quiz: 10 multiple-choice questions
Question 1
Which method maps a GET endpoint?
A. MapPost
B. MapGet
C. MapDeleteOnly
D. AddController
Correct answer: B
Explanation: MapGet maps a handler for HTTP GET requests.
Question 2
What does MapGroup("/api/products") do?
A. Creates a database table
B. Starts a separate server
C. Groups endpoints under a common route prefix and shared conventions
D. Automatically authorizes every user
Correct answer: C
Explanation: Route groups organize endpoints and can apply shared metadata or conventions. A prefix alone does not secure an endpoint.
Question 3
What is a common use for an endpoint filter?
A. Inspecting endpoint arguments or wrapping handler execution
B. Replacing the database engine
C. Compiling CSS
D. Creating a project file
Correct answer: A
Explanation: Endpoint filters run around Minimal API handler invocation and can inspect arguments and results.
Question 4
What does {id:int} mean in a route template?
A. The ID is always authorized
B. The database row must exist
C. The response is an integer
D. The route parameter is constrained to an integer
Correct answer: D
Explanation: The route constraint helps determine whether the route matches. Existence and authorization require separate checks.
Question 5
Which result is appropriate after successfully creating a resource?
A. Results.NotFound()
B. Results.Created(...)
C. Results.Unauthorized()
D. Results.BadRequest()
Correct answer: B
Explanation: HTTP 201 Created is commonly used when a resource has been created.
Question 6
How can a handler receive a registered service?
A. Only by reading a static field
B. By creating it with new every time
C. By declaring it as a handler parameter for DI resolution
D. Only through a query string
Correct answer: C
Explanation: Minimal API handler parameters can receive services registered with dependency injection.
Question 7
Why should APIs use request DTOs?
A. To expose every entity field
B. To disable routing
C. To avoid returning HTTP status codes
D. To define the accepted contract and reduce overposting risk
Correct answer: D
Explanation: Request DTOs limit the input shape and help prevent callers from setting unintended fields.
Question 8
Which is generally a better home for core business rules?
A. Application/domain services rather than only an endpoint filter
B. CSS files
C. The route prefix
D. The HTTP response header alone
Correct answer: A
Explanation: Business rules should remain valid across different entry points. Filters are useful for endpoint-level cross-cutting behavior.
Question 9
What does CancellationToken help with?
A. It automatically authenticates the client
B. It lets supported operations observe cancellation
C. It guarantees database transactions never fail
D. It replaces validation
Correct answer: B
Explanation: Passing cancellation tokens to downstream operations can prevent unnecessary work after cancellation.
Question 10
Does Minimal API automatically mean every endpoint is faster?
A. Yes, always
B. Only when the database is empty
C. No; performance depends on the entire request path
D. Only in development
Correct answer: C
Explanation: Minimal APIs reduce some programming-model ceremony, but database queries, serialization, and downstream calls still determine performance.
21. Summary
One-minute revision
Minimal APIs define HTTP endpoints directly with methods such as MapGet and MapPost. MapGroup organizes related routes and shared conventions. Endpoint filters wrap handler execution and can inspect arguments and results. Handlers can use DI, bind request values, call services, and return appropriate HTTP results.
Five-minute revision
- Minimal APIs are part of ASP.NET Core, not a separate server.
MapGet,MapPost,MapPut,MapPatch, andMapDeletemap HTTP method handlers.- Route templates describe URL patterns and route parameters.
- Parameter binding can read route, query, body, header, and DI values.
- Route constraints help match URLs but do not validate business rules or authorize resources.
MapGrouporganizes endpoints under a shared prefix and conventions.- Endpoint filters run around endpoint handler invocation.
- Middleware operates in the broader HTTP pipeline.
- Request DTOs and response DTOs define explicit API contracts.
- Use DI and services to keep handlers maintainable.
- Return accurate HTTP status codes and consistent errors.
- Secure and test endpoints as carefully as controller-based APIs.
Bullet-point summary
- Minimal APIs reduce ceremony for defining HTTP endpoints.
- Route groups improve organization and shared configuration.
- Endpoint filters are useful for endpoint-specific cross-cutting behavior.
- Core business rules belong in appropriate application/domain components.
- Use DTOs, validation, and authorization.
- Use async I/O and cancellation tokens for supported operations.
- Use OpenAPI to describe endpoint contracts.
- Integration-test the full HTTP pipeline.
- Measure performance rather than assuming the programming model guarantees it.
Memory tricks
- Map = Method + Route + Handler: understand what request the endpoint accepts and what code handles it.
- Group = Shared prefix + shared conventions: group related routes together.
- Filter = Before/after handler: inspect arguments, continue to the handler, and optionally inspect the result.
- Bind → Validate → Authorize → Execute → Respond: a useful checklist for request handling, remembering that framework authorization and binding occur in their configured pipeline stages.
Flashcards
| Front | Back |
|---|---|
What does MapGet do? | Maps a handler for HTTP GET |
What does MapPost do? | Maps a handler for HTTP POST |
What does MapGroup do? | Groups routes and shared endpoint conventions |
| What is an endpoint filter? | A wrapper around endpoint handler execution |
What does {id:int} do? | Adds an integer-constrained route parameter |
| Why use DTOs? | Define input/output contracts and reduce overposting |
What is Results.NotFound()? | An HTTP 404 result |
| Why pass a cancellation token? | Let supported downstream work observe cancellation |
22. Cheat sheet
| Need | Minimal API solution |
|---|---|
| Map GET | app.MapGet("/items", handler) |
| Map POST | app.MapPost("/items", handler) |
| Map PUT | app.MapPut("/items/{id:int}", handler) |
| Map PATCH | app.MapPatch("/items/{id:int}", handler) |
| Map DELETE | app.MapDelete("/items/{id:int}", handler) |
| Group routes | app.MapGroup("/api/items") |
| Require authorization | .RequireAuthorization() |
| Add a filter | .AddEndpointFilter<TFilter>() |
| Return 200 | TypedResults.Ok(value) |
| Return 201 | TypedResults.Created(uri, value) |
| Return 204 | TypedResults.NoContent() |
| Return 400 | TypedResults.BadRequest() or validation problem result |
| Return 404 | TypedResults.NotFound() |
| Inject a service | Declare the service in handler parameters |
| Bind query data | [FromQuery] when explicit binding is useful |
| Bind route data | [FromRoute] when explicit binding is useful |
| Bind JSON body | [FromBody] when explicit binding is useful |
| Generate OpenAPI | builder.Services.AddOpenApi() and app.MapOpenApi() |
| Improve large lists | Filter, project, paginate, and limit |
Minimal setup
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
var app = builder.Build();
app.UseHttpsRedirection();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.MapGet("/health", () => Results.Ok(new { status = "healthy" }));
app.Run();
This is a minimal illustration. A production API should configure authentication, authorization, exception handling, logging, rate limiting, and other controls appropriate to its exposure and requirements.
23. Comparison table
Minimal APIs vs controller-based Web APIs
| Aspect | Minimal APIs | Controller-based Web APIs |
|---|---|---|
| Endpoint definition | Direct route-handler mapping | Controller classes and action methods |
| Boilerplate | Often lower for straightforward endpoints | More conventional structure |
| Organization | Route groups and endpoint modules | Controllers and actions |
| DI | Supported | Supported |
| Model binding | Supported | Supported |
| Authorization | Endpoint metadata and policies | Attributes, policies, and filters |
| Cross-cutting endpoint logic | Endpoint filters and middleware | MVC filters and middleware |
| OpenAPI | Supported with endpoint metadata | Supported with API conventions and metadata |
| Best fit | Focused APIs and concise endpoint mapping | APIs benefiting from controller/action conventions |
Middleware vs endpoint filters
| Aspect | Middleware | Endpoint filter |
|---|---|---|
| Execution scope | Broader HTTP pipeline | Matching Minimal API endpoint |
| Access to handler arguments | No direct typed argument list | Yes |
| Best use | Exception handling, request pipeline concerns | Endpoint-level argument/result processing |
| Applied to | Requests reaching its pipeline position | Endpoints to which the filter is attached |
| Can replace authorization system? | No | No |
Results vs TypedResults
| Aspect | Results | TypedResults |
|---|---|---|
| Return style | Convenient result helpers | Concrete typed result helpers |
| Type clarity | May use common result abstractions | Makes result types explicit |
| Endpoint metadata | May need explicit response metadata in some cases | Can help describe response types |
| Best use | Concise handlers | Endpoints where explicit result types help |
24. Key takeaways
- Minimal APIs map HTTP methods and routes directly to handlers.
MapGetandMapPostare common building blocks for read and submit operations.MapGrouporganizes related endpoints and shared configuration.- Endpoint filters wrap handler execution and can inspect arguments and results.
- Middleware and endpoint filters serve different scopes.
- Parameter binding does not replace validation or authorization.
- DTOs help protect internal data and define stable API contracts.
- Use DI and application services to keep handlers focused.
- Return correct HTTP status codes and consistent error responses.
- Configure authentication, authorization, rate limits, and error handling according to risk.
- OpenAPI helps describe and maintain API contracts.
- Test endpoints through HTTP integration tests and measure performance.
25. Revision checklist
- I can explain Minimal APIs and their trade-offs.
- I can map GET and POST endpoints.
- I understand route templates and constraints.
- I can explain handler parameter binding.
- I can group routes with
MapGroup. - I understand endpoint filter execution.
- I can distinguish middleware from endpoint filters.
- I can use dependency injection in a handler.
- I can return appropriate status codes.
- I can design request and response DTOs.
- I understand validation and authorization boundaries.
- I can explain OpenAPI generation.
- I can test Minimal APIs through HTTP integration tests.
- I can identify performance and security risks.
26. Further reading
Continue with these related topics on the Logic Lense / .NET Interview Ready roadmap:
- ASP.NET Core Fundamentals roadmap
- Razor Pages (previous topic)
- MVC Pattern
- Routing in ASP.NET Core
- Middleware in ASP.NET Core
- Dependency Injection
- Service Lifetimes
- Configuration and
appsettings.json - Logging abstractions
- Authentication and Authorization
- REST API fundamentals
- Model Binding and Validation
- Entity Framework Core
Last updated 10/23/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
