What is Minimal API?

ASP.NET Core Minimal APIs provide a streamlined approach to developing web APIs with minimal code. They prioritize conciseness, focusing on the core functionality of handling HTTP requests and responses.

Here are some key aspects of Minimal APIs:

Let me explain with a CRUD example. (I have used .NET 9 as the target framework)

Create an ASP.NET Core Web API project with the following endpoints. In the program.cs file, add the following code.

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/api/apple/products",()=>Results.Ok("Get all Apple products"));
app.MapGet("/api/apple/products/{id}",(int id)=>Results.Ok($"Get Apple Product by id {id}"));
app.MapPost("/api/apple/products",()=>Results.Ok("Create an Apple product"));
app.MapPut("/api/apple/products/{id}",(int id)=>Results.Ok($"Update Apple product by id {id}"));
app.MapDelete("/api/apple/products/{id}",(int id)=>Results.Ok($"Delete Apple product by id {id}"));

app.Run();

Code Explanation

1. app.MapGet("/api/apple/products", () => Results.Ok("Get all Apple products"));

2. app.MapGet("/api/apple/products/{id}", (int id) => Results.Ok($"Get Apple Product by id {id}"));

3. app.MapPost("/api/apple/products", () => Results.Ok("Create an Apple product"));

4. app.MapPut("/api/apple/products/{id}", (int id) => Results.Ok($"Update Apple product by id {id}"));

5. app.MapDelete("/api/apple/products/{id}", (int id) => Results.Ok($"Delete Apple product by id {id}"));

Key Points

This is a basic example. In a real-world scenario, you would typically implement more complex logic within these endpoints, such as:

Organizing Minimal APIs with MapGroup

MapGroup is a powerful feature in Minimal APIs that allows you to group related endpoints under a common path. This improves organization and readability, especially as your API grows in complexity.

Let me organize the above endpoints with MapGroup.

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

var appleProductsGroup = app.MapGroup("/api/apple/products");

appleProductsGroup.MapGet("",()=>Results.Ok("Get all Apple products"));
appleProductsGroup.MapGet("{id}",(int id)=>Results.Ok($"Get Apple Product by id {id}"));
appleProductsGroup.MapPost("",()=>Results.Ok("Create an Apple product"));
appleProductsGroup.MapPut("{id}",(int id)=>Results.Ok($"Update Apple product by id {id}"));
appleProductsGroup.MapDelete("{id}",(int id)=>Results.Ok($"Delete Apple product by id {id}"));

app.Run();

var appleProductsGroup = app.MapGroup("/api/apple/products");

Key Benefits

Minimal APIs in ASP.NET Core provide a refreshing approach to building web APIs, emphasizing simplicity, efficiency, and a focus on core HTTP concepts.By employing MapGroup, you can establish a well-defined hierarchy within your Minimal API routes, facilitating better code organization and easier maintenance.

Happy Coding!