Minimal APIs in .NET
What?
Minimal APIs is one of the available programming models offered by Microsoft to create RESTful APIs in .NET.
The other mainly used programming model is using controllers.
Comparison
| Controllers | Minimal APIs |
---|
Structure | Classes (controllers) and class methods (actions) | Functions (any lambda or method) |
Configuration | Basic setup in startup. Main configuration through attributes (declarative) | Method calls, slight use of attributes |
Focus | Clear structure. Widely understood. | Flexible, little code needed |
Quick reference
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-8.0
A first look
will give you a minimalistic dotnet solution, with one project containing one Program.cs that looks like this:
You can run the project by using an IDE like Visual Studio, VS Code or Rider, or by using the command line:
Specifying routes
Route handlers
A route handler is what is being called, whenever a route matches the incoming request.
Route handlers can be a lambda expression, a local function, an instance method or a static method.
Route handlers can be synchronous or asynchronous.
Route handlers (2)
Structuring Minimal API projects
When Minimal API projects get larger it might be wise to structure them. They don’t have to be defined in Program.cs
.
Structuring Example
Route parameters
You can use a route pattern to specify parameters that are passed in as part of the URL
Route constraints
Parameter binding
Parameter binding is the process of converting request data into strongly typed parameters that are expressed by route handlers.
- Supported binding sources:
- Route values
- Query string
- Header
- Body (as JSON)
- Form values
- Services provided by dependency injection
Parameter binding example
Explicit parameter binding
Responses
Route handlers support the following types of return values:
Result Type | Behavior |
---|
IResult based | Framework calls IResult.ExecuteAsync |
string | Framework writes string directly to response |
T (Any other type) | Framework JSON-serializes the response |