Minimal APIs in .NET: Build Fast, Lightweight Web Services

What is Minimal API in .NET?

Minimal APIs are  a simplified, high performance approach for building HTTP APIs with ASP.NET core that require minimal code and configuration. Instead of the traditional, controller-based method, minimal APIs allow developers to define API endpoints directly in their project's primary file, such as program.cs
This approach, first introduced in .NET 6, is ideal for scenarios where a full-fledged MVC framework would be overkill, such as for microservices, serverless functions, and lightweight applications
Characteristics
  • Reduced boilerplate: A minimal API avoids the traditional scaffolding of controllers, action methods, and attributes, resulting in a more concise and streamlined codebase.
  • Concise syntax: Endpoints are declared using a functional style with lambda expressions and the map extension methods (mapget, mappost etc.), making the code brief and focused.
  • High performance: With fewer layers of abstraction and middleware, minimal APIs offer improved performance, lower latency, and reduced resource consumption.
  • Simplified setup: The configuration is straightforward, allowing developers to set up a new API project with fewer files and dependencies.
  • Integration with ASP.NET Core: Despite its lightweight nature, a minimal API has full access to the core features of ASP.NET Core, including dependency injection, middleware, and authentication.

Advantage of Minimal API
  • Less Boilerplate : No need for controller, attributes or multiple files to get started.
  • Fast Performance : Lower startup overhead and runtime execution path.
  • Cleaner Code : Espescially for samll APIs or microservices. Everything can be in one place or easily grouped.
  • Easier Testing : Endpoints cab be treated as pure functions.
  • Better for Microservices : Ideal for samll, focused service.
  • Support Grouping : You can use MapGroup() to organize endpoints cleanly.
  • All .NET features : Middleware, filters, DI, logging, EF Core, etc. fully supported

Disadvantage of Minimal API
  • Not idel for large project : Lack of structure for large scale apps unless you enfource patterns manually.
  • Less Familiar for MVC devs: Developers used to controllers and attributes may find it unfamiliar at first
  • Lack of built in validation/Binding Features : Compared to model binding and validation in mvc 
  • Fewer out of the box conventions : You have to define more manually- which is freedom, but also work

When to use Minimal API
  • You’re building microservices

  • You need a quick prototype

  • You’re building internal APIs

  • You want clean and simple APIs


Types of Minimal API Patterns

1. Inline Minimal API

Everything in Program.cs.

Good for: Demos, PoCs, very small apps.

var app = WebApplication.Create();
app.MapGet("/ping", () => "pong");
app.Run();


2. Grouped Minimal API

        Use MapGroup() to organize related routes.

        Good for: Medium apps, microservices.

            var todos = app.MapGroup("/todos");
            todos.MapGet("/", ...);
            todos.MapPost("/", ...);


3. Modular Minimal API

Split endpoint logic into separate files (like TodoEndpoint.cs), keeping Program.cs clean.

Good for: Production apps with maintainability in mind.

// In Program.cs
TodoEndpoints.Register(app);
// In TodoEndpoints.cs
public static class TodoEndpoints
{
public static void Register(IEndpointRouteBuilder app)
{
var group = app.MapGroup("/todos");
group.MapGet("/", ...);
group.MapPost("/", ...);
}
}


How to create Minimal API step by step guide:

Will create sample Minimal API project and perform CRUD operation with SQL Server database.

1.  Create Database and Table. Sample script as below. Execute on sql server.

     CREATE DATABASE minimalapi_db;

       Use minimalapi_db;

       CREATE TABLE dbo.Products

        (

[Id] [int] IDENTITY(1,1) NOT NULL Primary Key,

[ProductName] [nvarchar](50) NULL,

[ProductPrice] [decimal](10, 2) NULL

        );

2.  Create Web API project in visual studio.

    Hera I have creatd WEB API Project with .NET Core 9. Untick the user controller option click on create button to create project. I am visual studio 2026 Insider so my UI will be looks some what different than your visual studio.

 



3.  Configure swagger for better api view endpoints. Also add nuget packages that required for scaffold.
  • Microsoft.EntityFrameworkCore.SqlServer   
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.Tools
  • Swashbuckle.AspNetCore

4.  Add Connection string in appsetting.json and configure program.cs








5.  Write API in program. cs and  run and check 


    //Get All Products

app.MapGet("/api/product", (MinimalapiDbContext db) =>
{
    return Results.Ok(db.Products.ToList());
});

    //Get Product By Id
            app.MapGet("/api/product{id:int}", (MinimalapiDbContext db, int id) =>
            {
                return  db.Products.Find(id) is Product product ? Results.Ok(product) :Results.NotFound();
            });
    
    // Create Product

          app.MapPost("/api/product", (Product product, MinimalapiDbContext db) =>
{
    if (product.Id == 0)
    {
        db.Products.Add(product);
        db.SaveChanges();
        return Results.Created("Product added successfully!",product);
    }
    else
    {
        return Results.InternalServerError("Enter proper value!");
    }

});

    // Delete Product

app.MapDelete("/api/product/{id:int}", (MinimalapiDbContext db, int id) =>
{
    var product = db.Products.Find(id);
    if (product != null)
    {
        db.Products.Remove(product);
        db.SaveChanges();

        return Results.Ok("Product deleted successfull!");
    }
    else
    { 
        return Results.InternalServerError("Product data not found!");

    }
});




Click here to watch the YouTube video : URL

#dotnet #minimalapi #net9 #webapi #csharp #devlife

Comments

Popular posts from this blog

Understanding Middleware in .NET Core

Database Approaches in .NET Core: Code-First vs Database-First Explained for Beginners

Dev tunnels