Introduction to Minimal APIs in .NET
Minimal APIs Introduction
Minimal APIs were introduced were introduced in .NET 6 and more light weight than controllers.
Minimal APIs are a simplified approach for building fast HTTP APIs with ASP .NET Core
Pros and Cons
These are the benefits of using Minimal APIs:
-
Minimal APIs offer a more concise and focused syntax for defining routes, endpoints, and handling requests.
-
Traditional controllers often require a significant amount of boilerplate code to set up routes, actions, and parameter bindings. With Minimal APIs, this boilerplate is significantly reduced.
-
Minimal APIs use a functional-style syntax that allows you to define routes and endpoints using lambda expressions.
-
For small to medium-sized APIs, you can define your entire API in a single file, making it easier to manage and navigate your codebase.
-
Minimal APIs can speed up development cycles due to less code.
-
Minimal APIs allow you to define routes and actions without the need for separate controller classes.
Additionally Minimal APIs have some cons:
-
For complex scenarios where we need to put a lot of routes Minimal APIs are less flexible alternatively they are best fit for those Microservices where we create tiny APIs.
-
Testing can become difficult while using Minimal APIs because it is not as simple as we do for controllers.
-
We might face lack of resources/community/tools/libraries while working with Minimal APIs because these are quite new in .NET world
Replacing Controllers with Minimal APIs
We can use following methods of Web Application for CRUD operations:
-
MapGet
-
MapPut
-
MapPost
-
MapDelete
Each method takes two parameters a string(which is route path) and delegate(which could be anonymous type or strong type and empty as well)
Let’s look how its controller looks would be:
[ApiController]
[Route("Users")]
public class UsersController : ControllerBase
{
[HttpGet]
public string Get()
{
return $"Users retrieved";
}
[HttpPost]
public string Create(int rollNo, string userName)
{
return $"User with RollNo: {rollNo} and UserName: {userName} created";
}
[HttpPut]
public string Update(int rollNo, string userName)
{
return $"User with RollNo: {rollNo} and UserName: {userName} updated";
}
[HttpDelete]
public string Delete(int rollNo)
{
return $"User with RollNo: {rollNo} deleted";
}
}
Now we will replace it with Minimal APIs , instead of putting all this code in different controller file , we would put our code in Program.cs file.
var app = builder.Build();
app.MapGet("/GetUser", () =>
{
return $"Users retrieved";
});
app.MapPost("/CreateUser", (int RollNo, string UserName) =>
{
return $"User with RollNo: {RollNo} and UserName: {UserName} created";
});
app.MapDelete("/DeleteUser", (int RollNo) =>
{
return $"User with RollNo: {RollNo} deleted";
});
app.MapPut("/UpdateUser", (int RollNo, string UserName) =>
{
return $"User with RollNo: {RollNo} and UserName: {UserName} updated";
});
How to inject dependencies using Minimal API
Let’s update above example and now add IConfiguration in our API and retrieve a hardcoded username from appsetting (Just for the sake of demo).
Sometimes we need to inject IConfiguration or IHttpClientFactory then we can use it like this:
app.MapGet("/GetUsers", (int page, int pageSize, IConfiguration configuration) =>
{
string userName = configuration.GetValue<string>("UserName");
return $"Paginated Users retrieved for userName: {userName}";
});
How to make your Program.cs file cleaner
It seems fine if we have just 4-5 minimal APIs but what if you have larger number then Program.cs file would become messy and lengthy creating difficulties in managing it.
Create different method that handles delegate part (As I mentioned above Minimal APIs take route and delegate) then call that method. But still code would be in Program.cs file which I don’t want.
We can create regions as well to differentiate APIs aligned with a specific entity but it does not make our Program file cleaner.
Let’s create a extension method for each entity endpoints:
public static class UserEndPoint
{
public static void RegisterUserAPIs(this IEndpointRouteBuilder app)
{
app.MapGet("/GetUser", () =>
{
return $"Users retrieved";
});
app.MapPost("/CreateUser", [AllowAnonymous] async (int RollNo, string UserName) =>
{
string response = $"User with RollNo: {RollNo} created";
return await Task.FromResult(response);
});
app.MapDelete("/DeleteUser", (int RollNo) =>
{
return $"User with RollNo: {RollNo} deleted";
});
}
}
Now register it in Program file
using MinimalAPIDemo.EndPoints;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Register your Minimal APIs
app.RegisterUserAPIs();
app.RegisterTeacherAPIs();
Additionally you can check this video on “How To Organize Minimal API Endpoints Inside Of Clean Architecture”.
For more in depth knowledge check official docs of Microsoft
When should we use Minimal APIs
-
Simple application with a few routes
-
Microservices (with small number of routes)
GitHub Code
You can find code of this newsletter issue at this GitHub Repo .
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place