🚀 What Are Minimal APIs in .NET?

Minimal APIs were introduced in .NET 6 as a lightweight way to build HTTP APIs with minimal overhead. Unlike traditional ASP.NET Core Web APIs, Minimal APIs don’t require controllers, classes, or even attributes. You can define routes directly in your Program.cs file, making them ideal for microservices, quick prototypes, and small applications.

Minimal APIs prioritize simplicity, performance, and developer productivity.

🧠 Why Were Minimal APIs Introduced?

Traditional ASP.NET Core APIs come with a structured setup:

While powerful, this structure can be overkill for simple scenarios like:

Minimal APIs reduce the ceremony needed to get an API up and running.

🧱 Minimal API vs Traditional Web API

Feature Minimal API Traditional Web API
Project Structure Flat, single-file capable Controller-based, multi-file
Verbosity Minimal Verbose, boilerplate-heavy
Startup Time Faster Slightly slower
DI Support ✅ Yes ✅ Yes
OpenAPI/Swagger ✅ Yes (manually configured) ✅ Yes (automatic with controllers)
Best Use Case Microservices, lightweight APIs Large, complex applications

🛠️ How to Create a Minimal API in .NET

Here's how a basic Minimal API looks in .NET 6/7/8:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello, world!");
app.MapGet("/greet/{name}", (string name) => $"Hello, {name}!");
app.MapPost("/user", (User user) => $"User {user.Name} created.");

app.Run();

record User(string Name, int Age);

This all lives in your Program.cs. No controllers. No route attributes. Just straight-to-the-point endpoints.

🔐 Features Available in Minimal APIs

Even though they are "minimal," you can still use powerful ASP.NET Core features:

Example with Dependency Injection:

builder.Services.AddSingleton<IWeatherService, WeatherService>();

app.MapGet("/weather", (IWeatherService service) =>
{
    return service.GetForecast();
});

🧪 When Should You Use Minimal APIs?

✅ Use Minimal APIs When:

❌ Avoid Minimal APIs When:

📦 Minimal APIs + Swagger (OpenAPI)

To add Swagger UI in Minimal API projects:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

🔁 Real-World Use Case: Microservice Example

Product Service Example

app.MapGet("/products", () =>
{
    return new List<Product> {
        new("Laptop", 1500),
        new("Keyboard", 50)
    };
});

record Product(string Name, decimal Price);

Simple. Clean. No need to create a full-blown controller.

🧰 Tips for Scaling Minimal APIs

Route Group Example (.NET 7+)

var productRoutes = app.MapGroup("/products");

productRoutes.MapGet("/", GetProducts);
productRoutes.MapPost("/", AddProduct);

📝 Conclusion

Minimal APIs bring a fresh, lean approach to building APIs in .NET. While they’re not a one-size-fits-all solution, they are perfect when you need:

Use them wisely, especially when your project requirements align with their strengths.