Minimal APIs

Minimal API is introduced in .NET 6 to create APIs with the least possible dependencies. This new hosting model allows creating API with few lines of code and it’s inspired by existing successful frameworks like Express.js and Golang. It doesn’t use the MVC architectural pattern and leaves the developers’ hands open to implement their own preferred patterns.

Pros:

  • Easy and fast to bootstrap an API
  • Not limited to the only using MVC pattern
  • Slightly faster than MVC
  • Only have dependencies you need
  • Good for microservices

Cons:

  • Easier to have a bad architecture
  • Harder to manage big projects
  • Still new and can change a lot

Create a Minimal API With dotnet CLI

Type the following commands in your command prompt to create the project

dotnet new webapi -minimal -o HelloWorld
cd HelloWorld
code -r ../HelloWorld

Create a Minimal API With Visual Studio 2022

You need Visual Studio 2022 with ASP.NET and web development workload installed.

You should choose the ASP.NET Core Web API template.

Then choose the location for the project with the name you want to give to this project and solution.

Make sure you choose the Framework as .NET 6 or above, and leave the Use controllers (uncheck to use minimal APIs) unchecked

Program.js

You are going to have a Program.cs file with the following code, it comes with some default code for a working API with Swagger in place.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateTime.Now.AddDays(index),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.Run();

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

You can have your API up and running with the following few lines in the Program.js file; of course, it’s not a production-ready API but the same API would take much more lines of code in traditional MVC APIs.

//Bare minimum code you will need to run Minimal API
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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

app.Run();

Dependency Injection in Minimal APIs

The injections should happen before the var app = builder.Build(); and it can be passed to the endpoint’s Lambda Expression.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<IUserService, UserService>();

var app = builder.Build();

app.MapGet("/users", async (IUserService userService) 
    => await userService.GetUsers());

app.Run();

Implementing Endpoints

You should define the endpoints after the var app = builder.Build(); line. The app object has MapGet, MapPost, MapPut, and MapDelete Methods for Implementing Rest API’s Get, Post, Put, and Delete methods. Interestingly, there is no MapPatch Method implemented in the object. These Methods accept 2 Arguments, first one is the routing for the endpoint and the second one is a Lambada Expression that runs when the endpoint is being hit.

app.MapGet("/users", async (IUserService userService) 
    => await userService.GetUsers());

app.MapGet("/users/{id:int}", async (int id, IUserService userService) => 
await userService.GetUser(id));

app.MapPost("/users", async (UserRequest user, IUserService userService) 
    => await userService.CreateUser(user));

app.MapDelete("/users/{id:int}", async (int id, IUserService userService)
    => await userService.DeleteUser(id));

app.MapPut("/users/{id:int}", async (int id, IUserService userService)
    => await userService.UpdateUser(id));

Minimal APIs are the new path Microsoft has chosen and I believe we will see more improvements and new features in the coming years. Definitely, we should try to use them where it serves well.

This was a brief introduction to Minimal APIs, and I will probably write more about it in future posts. Hope you enjoyed it.