Minimal APIs in C#

With the arrival of .NET 6, C# allows us to create what are called "minimal APIs", which are basically the adaptation of what we already had in .NET 5 with Top level programs to APIs.

 

In this video, we will see how to create and use minimal APIs, as well as my personal opinion.

 

 

 

1 - My personal opinion on minimal APIs

First of all, I want to start with my personal opinion. This is because I have spent some time thinking about this new language feature and have finally formed an opinion about it.

 

Since the arrival of .NET 5 and its top level programs, I already saw that something like this was coming, and I'm not sure it's beneficial in the long run for developers. Let me explain, both top level programs and minimal APIs are great features to attract new developers to the language, but with them, it's very difficult to make large applications.

 

For example, one use case I do see is for making small applications, like scripts you would write in other languages like Python or for example serverless functions. Personally, I have experience with NodeJS and my experience is that it was very easy to create serverless functions on AWS when they were small, whereas in C# I had a project, needed to compile, etc.; in NodeJS it was just a simple file with 30 lines.

 

But this is just my opinion, based on my personal experience. Microsoft has a team to decide on features, who have surely thought of many other use cases. Still, I think the main goal is to attract new users, which is good.

 

I'd love to know your opinion if you want to share it; you can reply to this tweet.

 

 

2 - Creating a minimal API in C#

For now (August 2021), .NET 6 is still in preview and is not available as a template in any version of Visual Studio or another IDE. The only way to create a minimal api is through the command line with the following command:

dotnet new web -o MinimalApi
  • Note: Alternatively, you can create all the files manually. You will need program.cs, .csproj, and appsettings.json.
  • Note2: Another option is to create a console application, change the targetFramework to .net6.0 and delete all the content from program.cs
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <LangVersion>preview</LangVersion>
  </PropertyGroup>
</Project>

 

And if we have created our minimal application using the command above, our program.cs will contain the following code:

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;

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

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.MapGet("/", () => "Hola NetMentor!");

app.Run();

 

In the code given, we have everything we need to run it from the command line with the command dotnet run and this would be the result:

minimal api result

The reason the code works is that Microsoft.AspNetCore.Builder provides a class called WebApplication that contains a method CreateBuilder. Once we build it using .build(), it generates the HTTP pipeline, which allows us to receive HTTP/HTTPS calls.

 

And, along with the pipeline, we have extension methods Map, MapGet, MapPost, MapPut, which receive a pattern that acts as the URL we expect, and a delegate to execute the specified action.

In our case, it would be the following:

app.MapGet("/", () => "Hola Netmentor!");

app.MapGet("/{id}", (string id) => $"Simulación del id: {id}");

One endpoint is simply our URL and the other is url/id which prints a message.

 

 

3 - Other possible features with Minimal APIs

Minimal APIs are complete applications, so we can do whatever we want with them; we can create classes and processes as we would in any other type of application.

 

Therefore, we can implement third-party applications such as AutoMapper, Dapper for our SQL connections, or even dependency injection if we include the Microsoft.Extensions.DependencyInjection.Abstractions package. But, as I mentioned before, I think including many classes in our minimal APIs is counterproductive. For large applications, I see using our normal APIs as a more suitable solution.

 

3.1 Add swagger to a minimal API

To add support for swagger all we have to do is include the Swashbuckle.AspNetCore package and add a couple of lines to our code:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();  //<- this line
builder.Services.AddSwaggerGen(); //<- this line
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseSwagger(); //<- this line

app.MapGet("/", () => "Hola NetMentor!");
app.UseSwaggerUI();  //<- this line
app.Run();

Now we just need to go to the endpoint https://localhost:5001/swagger to see the swagger interface.

 

swagger in minimal api

 

Conclusion

  • In this post, I shared my opinion on minimal APIs and top level programs.
  • How to create minimal APIs in C#
This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café