🚀 APIs in 10 Lines of Code
MVC Controllers for simple API? Overkill. Minimal APIs (.NET 6+) create HTTP endpoints with minimal ceremony. Perfect for microservices, simple APIs.
❌ Traditional Controller
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public async Task> Get()
{
return await _service.GetAllAsync();
}
[HttpPost]
public async Task Post(User user)
{
return await _service.CreateAsync(user);
}
}
✅ Minimal API
var builder = WebApplication.CreateBuilder(args); builder.Services.AddScoped(); var app = builder.Build(); app.MapGet("/api/users", async (IUserService service) => await service.GetAllAsync()); app.MapPost("/api/users", async (User user, IUserService service) => await service.CreateAsync(user)); app.Run(); // Everything in Program.cs!
🎯 Complete CRUD Example
// GET by ID
app.MapGet("/api/users/{id:int}", async (int id, IUserRepository repo) =>
{
var user = await repo.GetByIdAsync(id);
return user is not null ? Results.Ok(user) : Results.NotFound();
});
// PUT update
app.MapPut("/api/users/{id:int}", async (int id, User user, IUserRepository repo) =>
{
var existing = await repo.GetByIdAsync(id);
if (existing is null) return Results.NotFound();
user.Id = id;
await repo.UpdateAsync(user);
return Results.NoContent();
});
// DELETE
app.MapDelete("/api/users/{id:int}", async (int id, IUserRepository repo) =>
{
var deleted = await repo.DeleteAsync(id);
return deleted ? Results.NoContent() : Results.NotFound();
});
🔐 Authentication & Authorization
// Require authentication
app.MapGet("/api/profile", async (HttpContext context) =>
{
return Results.Ok(new { user = context.User.Identity?.Name });
})
.RequireAuthorization();
// Require specific role
app.MapDelete("/api/users/{id}", async (int id) =>
{
await repo.DeleteAsync(id);
return Results.NoContent();
})
.RequireAuthorization("AdminOnly");
💡 Pro Tips
- Use route groups: Group related endpoints with MapGroup
- Add Swagger: builder.Services.AddEndpointsApiExplorer()
- Organize endpoints: Use extension methods for large apps
- Add filters: .AddEndpointFilter() for cross-cutting concerns
- Use Results: Results.Ok(), Results.NotFound() for typed responses
“Rewrote microservice API from MVC to Minimal APIs. Code reduced from 500 lines across 5 files to 150 lines in Program.cs. Startup time halved. Easier for juniors to understand.”
