Introduction

With the release of .NET 6, Microsoft introduced Minimal APIs, a simplified way to build HTTP APIs with less boilerplate and more focus on functionality. Minimal APIs are ideal for microservices, lightweight APIs, and rapid prototyping.

In this article, we will explore:

What Are Minimal APIs?

Minimal APIs allow developers to create RESTful services without controllers, startup classes, or complex configurations. Everything can be defined in the Program.cs file.

They are:

Why Minimal APIs?

Traditional Web APIs require:

Minimal APIs reduce this complexity by enabling you to define endpoints directly using lambda expressions.

Benefits:

Creating a Minimal API in .NET Core

Step 1: Create a New Project

Use the following command:

dotnet new web -n MinimalApiDemo

Open the project in Visual Studio or VS Code.

Step 2: Program.cs Example

Here is a simple Minimal API example:

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

app.MapGet("/", () => "Welcome to Minimal API!");

app.MapGet("/hello/{name}", (string name) =>
{
    return $"Hello, {name}!";
});

app.Run();

Step 3: Run the Application

Run the project and navigate to:

HTTP Methods in Minimal APIs

app.MapGet("/users", () => "Get all users");

app.MapPost("/users", (User user) => $"User {user.Name} created");

app.MapPut("/users/{id}", (int id, User user) =>
    $"User {id} updated");

app.MapDelete("/users/{id}", (int id) =>
    $"User {id} deleted");

Model Binding Example

public record User(int Id, string Name, string Email);

Minimal APIs automatically bind request data to models.

Dependency Injection in Minimal APIs

builder.Services.AddScoped<IUserService, UserService>();

app.MapGet("/service", (IUserService service) =>
{
    return service.GetMessage();
});

When Should You Use Minimal APIs?

Not ideal for very large, complex enterprise applications

Minimal APIs vs Controller-Based APIs

FeatureMinimal APIsController APIs
BoilerplateVery LowHigh
Learning CurveEasyModerate
PerformanceHighGood
StructureFlatLayered

Conclusion

Minimal APIs provide a modern, clean, and efficient way to build APIs in .NET. They reduce complexity while maintaining power and flexibility. If your application does not require heavy architecture, Minimal APIs are an excellent choice.