A Minimal API lets you define endpoints directly in Program.cs using simple methods.
Example
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World");
app.MapGet("/products/{id}", (int id) =>
{
return $"Product Id: {id}";
});
app.Run();
What’s happening?
MapGet → defines an HTTP GET endpoint- No controller, no action methods
- Everything is defined inline
Key Features
1. Less boilerplate
No need for:
- Controllers
- Attributes like
[HttpGet]
2. Fast to build
- Great for small APIs
- Quick prototypes
3. Built-in dependency injection
app.MapGet("/data", (IMyService service) =>
{
return service.GetData();
});
4. Supports all HTTP methods
app.MapPost("/products", (Product p) => { });
app.MapPut("/products/{id}", (int id) => { });
app.MapDelete("/products/{id}", (int id) => { });
Minimal API vs Controller API
| Feature | Minimal API | Controller API |
|---|---|---|
| Code size | Very small | More boilerplate |
| Structure | Flat | Layered (Controllers) |
| Best for | Small / simple APIs | Large / enterprise apps |
| Flexibility | Moderate | High |
When to Use Minimal API?
Good for:
- Microservices
- Simple CRUD APIs
- Prototypes
- Serverless functions
Not ideal for:
- Large complex applications
- Apps needing strict architecture (Controllers, Filters, etc.)
Real-World Example
app.MapGet("/users/{id}", async (int id, AppDbContext db) =>
{
var user = await db.Users.FindAsync(id);
return user is not null ? Results.Ok(user) : Results.NotFound();
});
Analogy
- Minimal API = writing a quick note
- Controller API = writing a structured document
Key Takeaway
Minimal API:
- Removes ceremony
- Focuses on simplicity and speed
- Still uses full power of ASP.NET Core under the hood
No comments:
Post a Comment