Sunday, April 5, 2026

Dotnet | Minimal API

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

FeatureMinimal APIController API
Code sizeVery smallMore boilerplate
StructureFlatLayered (Controllers)
Best forSmall / simple APIsLarge / enterprise apps
FlexibilityModerateHigh

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

Node | Cluster Vs Worker Threads

Cluster: Multiple processes (scale app across CPU cores) Worker Threads: Multiple threads (handle CPU-heavy work inside one process) Cluster...