⚡ Build APIs in 5 Lines of Code
Skip controllers, routing, Startup.cs. Minimal APIs (.NET 6+) make simple endpoints incredibly simple.
Traditional Controller Way
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
// UsersController.cs
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(new[] { "Alice", "Bob" });
}
// 20+ lines for simple endpoint
Minimal API Way
// Program.cs - That's it!
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/api/users", () => new[] { "Alice", "Bob" });
app.Run();
// 5 lines total ✨
🎯 Real-World Example
var builder = WebApplication.CreateBuilder(args); // Add services builder.Services.AddDbContext(); builder.Services.AddScoped (); var app = builder.Build(); // GET endpoint app.MapGet("/api/users", async (AppDbContext db) => await db.Users.ToListAsync()); // GET with route parameter app.MapGet("/api/users/{id}", async (int id, AppDbContext db) => await db.Users.FindAsync(id) is User user ? Results.Ok(user) : Results.NotFound()); // POST endpoint app.MapPost("/api/users", async (User user, AppDbContext db) => { db.Users.Add(user); await db.SaveChangesAsync(); return Results.Created($"/api/users/{user.Id}", user); }); // PUT endpoint app.MapPut("/api/users/{id}", async (int id, User updated, AppDbContext db) => { var user = await db.Users.FindAsync(id); if (user is null) return Results.NotFound(); user.Name = updated.Name; await db.SaveChangesAsync(); return Results.Ok(user); }); // DELETE endpoint app.MapDelete("/api/users/{id}", async (int id, AppDbContext db) => { var user = await db.Users.FindAsync(id); if (user is null) return Results.NotFound(); db.Users.Remove(user); await db.SaveChangesAsync(); return Results.NoContent(); }); app.Run();
✅ When to Use Minimal APIs
- Microservices: Small, focused services
- Prototypes: Quick MVP development
- Simple APIs: 5-10 endpoints max
- Serverless: Azure Functions, AWS Lambda
⚠️ When to Use Controllers
- Large APIs: 50+ endpoints
- Complex routing: Attribute routing, versioning
- Filters: Heavy use of action filters
- Team preference: Team familiar with MVC pattern
“Migrated webhook receiver from controller to Minimal API. 40 lines became 8. Performance identical. Startup time 30% faster. Perfect for small services.”
