Getting Started with Minimal APIs in .NET Core

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 Minimal APIs are

  • Why they were they introduced

  • How to create a Minimal API

  • When to use them

  • A simple working example

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:

  • Lightweight

  • Fast to develop

  • Easy to read

  • Perfect for small to medium APIs

Why Minimal APIs?

Traditional Web APIs require:

  • Controllers

  • Attributes

  • Dependency injection setup

  • Multiple files

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

Benefits:

  • Less boilerplate code

  • Improved performance

  • Easy learning curve

  • Clean and concise syntax

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:

  • https://localhost:5001/

  • https://localhost:5001/hello/John

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?

  • Microservices

  • Lightweight REST APIs

  • Prototypes & PoCs

  • Serverless applications

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.