.NET 6 - Minimal APIs
Tags: net6, minimalapi, csharp, rest
Published: 2021-10-10 14:39:57

## 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.
>
> -- <cite>[Dictionary.com][1]</cite>

[1]: https://www.dictionary.com/browse/minimalism

![Example of a white minimalist table, containing a lamp, a potted plant and an analog clock on the wall.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iurw8a443l61zjrd47gx.jpg)

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](https://expressjs.com) 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**](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/top-level-statements) 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](https://visualstudio.microsoft.com/vs/preview/). 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:

```powershell
dotnet new web -o dotnet-mininal-api
```

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

![Print from Visual Studio Solution Explorer with project open](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l3yi8mp7ikb8vgoyn0zi.png)

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**](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/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.

```csharp
public record Sales(long Id, DateTime DataTime, string Product, double Price);
```

#### 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*

```powershell
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
```

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

```csharp
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;");

}
```

Now we just need to instantiate our context:

```csharp
builder.Services.AddDbContext<dbContext>();
```
#### 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](https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations?view=aspnetcore-5.0), 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.

```powershell
dotnet tool install --global dotnet-ef
```

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

```powershell
dotnet ef migrations add Initial
```

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.

```powershell
dotnet ef database update
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hks6g6bhjtd8ulzjr8qp.png)

#### 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**](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0#endpoint) 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**](https://github.com/andersonpereiradossantos/dotnet-api-minimal) 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.

```csharp
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();
});
```

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.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fml7pgm5q5misold14qw.png)

### Repository

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

[Repository](https://github.com/andersonpereiradossantos/dotnet-api-minimal)

### 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](https://benfoster.io/blog/mvc-to-minimal-apis-aspnet-6/)
[Building Minimal APIs In .NET 6](https://dotnetcoretutorials.com/2021/07/16/building-minimal-apis-in-net-6/)
[Minimal APIs in ASP.NET Core 6.0](https://dotnetthoughts.net/minimal-api-in-aspnet-core-mvc6/)

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

[Linkedin](https://www.linkedin.com/in/andersonpereirasantos) • [Github](https://github.com/andersonpereiradossantos) • [Twitter](https://twitter.com/andersonpersann)