DEV Community

Cover image for .NET 6 - Minimal APIs
Anderson Pereira dos Santos
Anderson Pereira dos Santos

Posted on

.NET 6 - Minimal APIs

Introduction

You may have heard about minimalism around, and if not, speaking in a very superficial way, it refers to reducing and/or simplifying as much as possible what is unnecessary and keeping only the essentials to achieve the same goal or a higher, in other words "less is more", or according to the dictionary:

minimalistic is used to describe something that is stripped down to its most essential elements or uses only what is needed.

-- Dictionary.com

Example of a white minimalist table, containing a lamp, a potted plant and an analog clock on the wall.

But today I didn't come to explain what minimalism is, but I'll explain how it's possible to apply this concept to the development of API's with the new .NET 6.

Minimal API

.NET 6 brings with it the possibility of implementing Minimal APIs, the concept itself is not new, Node.JS Express has been doing this for years, however when it comes to .NET, it is something new.

The idea is relatively simple, it consists of implementing an API without the need for several components and lines of code, starting from .NET 5 when the top level was added, which allowed the construction of classes without having to add blocks with the namespace and nor the main method, thus reducing lines of code, this is just an example of the change.

Hands on

I've said too much, let's implement our first minimal API. First of all we will need to download the version of Visual Studio 2022 Community which is also in the Preview version, you can download it through this link. Perform standard installation by adding "ASP.NET and Web Development" functionality.

Creating the project

Now let's go to the best part, create our first Minimal API, in your terminal run the following command line in the folder you want to create, this will create a project with the basics to work:

dotnet new web -o dotnet-mininal-api
Enter fullscreen mode Exit fullscreen mode

Okay, your project will be created and should have this structure:

Print from Visual Studio Solution Explorer with project open

At first glance you will notice in your project, it is the amount of elements that will contain inside it, which as previously said will be the basic for you to have your API, and for those who already used the previous versions you can notice that the file "Startup.cs " no longer exists for this template, and everything you'll need so far is contained in the "Program.cs" file.

Records

Let's define our model, for that I'll use a resource already existing in C# 9, called record, which allows working with immutable objects, besides its specification is simple to be implemented and as we want a simple API we will make use of this resource by adding the following line of code at the end of Program.cs.

public record Sales(long Id, DateTime DataTime, string Product, double Price);
Enter fullscreen mode Exit fullscreen mode

Database connection

No secret here either, as in this project I'm using SQL Server, we'll make the connection to it, but it could be another database, for that we'll use the Entity Framework Core SQL Server

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Enter fullscreen mode Exit fullscreen mode

And we'll add this code snippet to our "Program.cs", remembering the need to change the connection string to connect to your database.

public class dbContext : DbContex
{    
    public DbSet<Sales> Sales {  get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer("Server=YourHost;Database=Company;User Id=YourUser;Password=YourPassword;");

}
Enter fullscreen mode Exit fullscreen mode

Now we just need to instantiate our context:

builder.Services.AddDbContext<dbContext>();
Enter fullscreen mode Exit fullscreen mode

Migrations

I'll be succinct at this step as it demonstrates how migrations work, it's not the purpose of the article, you can learn better through this Microsoft article, but to get ahead run these commands sequentially on your terminal:

If you don't have the tool installed, run this command in your terminal, otherwise go to the next one.

dotnet tool install --global dotnet-ef
Enter fullscreen mode Exit fullscreen mode

In the terminal, already in your project folder, execute this command so that it creates the migration files:

dotnet ef migrations add Initial
Enter fullscreen mode Exit fullscreen mode

If all goes well a suffice called "Migrations" should exist in your project with the generated scripts. If you have experienced an error, check your connection string if it is pointing to the bank correctly.

Finally run this command to create the database and its table structure and fields.

dotnet ef database update
Enter fullscreen mode Exit fullscreen mode

If everything is correct, at this moment you will have a new database created called Company and two tables created, one for controlling migrations and another called "Sales".

Printscreen from SQL Server with the structure of the database that was created

Creating the services

Well, if you've come this far now we will implement the GET method, to manipulate data from our sales model, we will make use of the endpoints that already exist in C# 9, but improved in C# 10, and through them we can implement complete methods that will be accessed directly via URLs defined directly in the method signature.

I won't put the code for the POST, PUT and DELETE methods here, as the article would have a lot of information, but on this link you can access the repository with everything explained and implemented here and with the other methods.

Just to put it in context, I'll demonstrate how the GET method works to get a sale by id.

app.MapGet("/sales/{id}", async (long id, dbContext db) =
{
    Sales sales = await db.Sales.FindAsync(id);


    if(sales != null)
        return Results.Ok(sales);

    return Results.NotFound();
});
Enter fullscreen mode Exit fullscreen mode

In MapGet we add the string with the service route "/sales/{id}", and between the keys we define the parameters that we receive via URL, in this case the id. Also, we'll pass in an Id and dbContext that we instantiated earlier.

We perform the query normally and return code 200 with the result or code 404 in case we don't find results for the searched id.

Extra

If you wanted, you can add Swagger just to test the API more easily, in the repository I've already left it implemented in case you want to test.

Printscreen from Swagger with all implemented methods contained in the repository.

Repository

Access the repository with the complete project through the link below, enjoy and follow me on Github, I'm always posting some useful stuff.

Repository

Conclusion

The concept is quite simple and easy to be implemented, if we wanted this example, we could have separated the model in a model folder as we are used to, and maybe added a controller, however maybe it would lose the essence of a Minimal API. I believe this concept can be very useful for implementations that were thought to be small and simple, but more robust API's and with many more rules, a more elaborate template will provide much more organization to the project.

References

From MVC to Minimal APIs with ASP.NET Core 6.0
Building Minimal APIs In .NET 6
Minimal APIs in ASP.NET Core 6.0

Thanks for reading. Follow me on my networks for more information:

LinkedinGithubTwitter

Top comments (1)

Collapse
 
joedotnot profile image
joedotnot

Do you (or anyone else) know how to return a specific Http Error code (For example, 422 or 418) from a minimal API, and capture it client-side with any client library?