aspnetcore-minimal-api

What is and how to use Minimal API in ASP.NET

  • 3 min

Minimal APIs are a simplified approach to building HTTP APIs in ASP.NET, offering a concise and functional syntax.

They are a feature introduced with .NET 6 to create RESTful APIs with minimal code and configuration. (just like many other frameworks).

This approach eliminates the need for traditional controllers, allowing us to define endpoints directly in the main configuration file.

When to Use Them?

  • ✅ APIs with few endpoints (e.g., microservices).
  • ✅ Rapid prototyping.
  • ✅ Integration with modern frontends (React, Vue, Angular).

### **When to Avoid Them** - ❌ Large projects with **complex logic** (better to use Controller-based APIs).

How to use Minimal APIs

To start using Minimal APIs, we simply need to create a project using the appropriate template.

dotnet new web -o MinimalApiDemo
cd MinimalApiDemo

This command will create a new Minimal API project with the basic folder and file structure needed.

If we now look at the Program.cs file, we will see that it already contains a first draft of a Minimal API,

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

app.MapGet("/", () => "Welcome to my minimal API mimal");

app.Run();

As we can see, it only has a mapping for Root that returns the text Welcome to my minimal API mimal

We can use this as a base and replace it with our own endpoints. 👇

Defining Endpoints

In Minimal API, endpoints are defined directly in Program.cs using methods like MapGet, MapPost, etc. These methods are:

HTTP VerbMinimal API MethodDescription
GETMapGetRetrieve data
POSTMapPostCreate a resource
PUTMapPutUpdate a resource
DELETEMapDeleteDelete a resource
PATCHMapPatchPartial update
HEADMapMethodsRequest metadata

Here you have an example of how each of them would be used,

var app = WebApplication.Create();

// GET
app.MapGet("/users", () => "List of users");

// POST
app.MapPost("/users", (User user) => Results.Created($"/users/{user.Id}", user));

// PUT
app.MapPut("/users/{id}", (int id, User user) => 
{
    // Update logic
    return Results.Ok(user);
});

// DELETE
app.MapDelete("/users/{id}", (int id) => 
{
    // Delete logic
    return Results.NoContent();
});

app.Run();

Parameters and Validation

Minimal API allows receiving parameters in multiple ways. ASP.NET automatically injects parameters from:

SourceExampleDescription
Route/users/{id}(int id)Extracts values from the URL
Query String/users?name=John(string name)Parameters in the URL
Body (JSON)app.MapPost("/users", (User user) => ...)Data in the request body
Headers(HttpRequest req) => req.Headers["Authorization"]HTTP headers
Services(IUserService service) => service.GetUsers()Dependency injection

For example,

app.MapGet("/search", (string name, int? page) => 
{
    // name → Query String (e.g., /search?name=John)
    // page → Optional Query String (e.g., /search?name=John&page=2)
    return Results.Ok(new { name, page });
});

app.MapPost("/upload", (IFormFile file) => 
{
    // File sent in the body (multipart/form-data)
    return Results.Ok($"File {file.FileName} uploaded");
});

Integration with Dependency Injection

Minimal API natively supports dependency injection (DI). We simply need to do the following,

Define a service in its file.

public interface IUserService
{
   List<User> GetUsers();
}

public class UserService : IUserService
{
   public List<User> GetUsers() => new() { new User(1, "John") };
}

Register it in the DI container

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IUserService, UserService>();

Inject it into an endpoint

app.MapGet("/users", (IUserService service) => service.GetUsers());