April 28, 2023

Minimal Api

Minimal API in .NET Core is a new approach to building web APIs with minimal ceremony and less boilerplate code. It is a feature that was introduced in .NET 6 and has been improved in subsequent versions, including .NET 7.

With Minimal API, developers can create HTTP endpoints with fewer lines of code and without having to set up complex routing or middleware configurations. This is achieved by providing a simplified syntax for defining endpoints, which reduces the amount of code required to create an API.

A simple example:


    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;

    var builder = WebApplication.CreateBuilder(args);

    var app = builder.Build();

    app.MapGet("/", () => "Hello World!");

    app.Run();

The goal of Minimal API is to enable developers to focus on writing business logic rather than dealing with infrastructure concerns. It provides a streamlined development experience, making it easier and faster to build APIs. Additionally, Minimal API integrates seamlessly with other .NET Core technologies, such as Dependency Injection and Entity Framework Core.

Another example for coherent code structure:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapPost("/change-password", UserEndpoints.ChangePassword);

app.Run();

public static class UserEndpoints
{
public static async Task<IResult> ChangePassword(
                                    HttpContext context,
                                    ChangePasswordRequest request,
                            IUserService userService)
{
//Logic here
return await Task.FromResult(Results.Ok());
}
}

Overall, Minimal API in .NET Core provides a lightweight, modern approach to building web APIs, enabling developers to quickly create high-performance, scalable APIs with minimal effort. 

I will be writing quite a bit of minimal api usages and best practices in future. So stay tuned.  

No comments: