Skip to content
Bruno Sonnino
Menu
  • Home
  • About
Menu

Creating RESTful APIs with Minimal APIs and Entity Framework Core in ASP.NET

Posted on 4 June 2023

Introduction

Some time ago, I wrote this article about FeatherHTTP. Things have evolved since then and, in .NET 6, Microsoft introduced a new approach called "Minimal APIs" which simplifies the process of build RESTful APIs. This article will guide you through the process of creating RESTful APIs using Minimal APIs in ASP.NET, highlighting its simplicity and efficiency.

What are Minimal APIs?

Minimal APIs in ASP.NET are a lightweight approach to building APIs with minimal ceremony. They allow you to define routes and endpoints using a concise syntax, reducing the amount of boilerplate code traditionally required. This approach makes it easier to build APIs quickly and with a smaller code footprint.

Setting up the Project

To get started, make sure you have .NET 6 or a higher version installed. Create a new ASP.NET project using the web template. Open a terminal window and execute the following command:

dotnet new web -o MinimalApi
Dos

This will create a new ASP.NET project named MinimalApi using the Minimal API template.

If you open the code, you will see that the generated project is very simple:

It contains the project file, the main file and two files with the settings. If you take a look at Program.cs, you will see something like this:

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

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

app.Run();
C#

When you run it, you will get a very simple service that answers with "Hello World!":

Defining Routes and Endpoints

In Minimal APIs, you define routes and endpoints using lambda expressions and the app.Map* methods provided by the WebApplication class. We will modify this project to create the weather forecast service, like we did in the previous article. For that, change the code in Program.cs to:

using System.Text.Json;

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

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

var rnd = new System.Random();
app.MapGet("/", () => Enumerable.Range(1, 5)
        .Select(index => new WeatherForecast(DateTime.Now.AddDays(index), 
            rnd.Next(-20, 55), 
            Summaries[rnd.Next(Summaries.Length)])));

app.Run();

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

When you run it and call the server, you will get a json array of temperatures:

Now, we can add Swagger to the API. To do this, we have to add the package Swashbuckle.AspNetCore to the project:

dotnet add package Swashbuckle.AspNetCore
Dos

Open the Program.cs file and modify the program as follows:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

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

app.UseSwagger();

var rnd = new System.Random();
app.MapGet("/", () => Enumerable.Range(1, 5)
        .Select(index => new WeatherForecast(DateTime.Now.AddDays(index), 
            rnd.Next(-20, 55), 
            Summaries[rnd.Next(Summaries.Length)])));

app.UseSwaggerUI();

app.Run();
C#

When you run the program and go to https://localhost:7035/swagger (the port should be different), you will get the Swagger page:

In this example, we use the MapGet method to define a route for the GET HTTP method at the path "/". When a request is made to this route, the lambda expression is executed, which returns 5 generated weather forecasts.

This is something simple, but we will see that the minimal API can also handle more complicated requests. We'll create a server that uses EF Core with a SQLite database to manage a table of customers. It will be able to create, update or delete customers using different endpoints.

Implementing the CRUD Service with EF Core

To start our project, create a new web project, add the Swashbuckle.AspNetCore, Microsoft.EntityFrameworkCore.Sqlite and Microsoft.EntityFrameworkCore.Tools packages to the project:

dotnet new web -o CustomerService
cd CustomerService
dotnet add package SwashBuckle.AspnetCore
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Tools
Dos

Now we will setup the infrastructure for our service, by adding a new file named Customer.cs with this code:

using System.Text.Json;
using Microsoft.EntityFrameworkCore;

public record Customer(string Id, string Name, string Address, string City, string Country, string Phone);

public class CustomerDbContext : DbContext
{
    public CustomerDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<Customer> Customer { get; set; }

    override protected void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseSqlite("Data Source=customer.db");
}
C#

The Customer class represents a customer entity. It has six properties that correspond to the customer's id, name, address, city, country, and phone number. The CustomerDbContext class is a database context class that provides access to the Customer entities in the database. It inherits from the DbContext class provided by the Entity Framework Core library. We are overriding the OnConfiguring method to use the SQLite database named customer.db.

The DbSet property in the CustomerDbContext class represents a collection of Customer entities in the database. It allows developers to query, insert, update, and delete Customer entities using LINQ queries or Entity Framework Core APIs.

With that in place, we can add the first endpoint, which retrieves all customers. We will also add Swagger to the project, to allow us to test the service:

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<CustomerDbContext>();

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

// Ensure database is created during application startup
using (var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<CustomerDbContext>();
    await dbContext.Database.EnsureCreatedAsync();
}

app.MapGet("/customers", async (CustomerDbContext context) =>
{
    return await context.Customer.ToListAsync();
});

app.MapGet("/customers/{id}", async (string id, CustomerDbContext context) =>
{
    var customer = await context.Customer.FindAsync(id);
    if (customer == null)
    {
        return Results.NotFound();
    }

    return Results.Ok(customer);
});

app.Run();
C#

We are adding the Swagger services, like before, then we add the DbContext, to use EF Core.

After that, we get the DbContext from the service provider and we ensure that the database is created at start.

Then, we set two endpoints, /customers and customers/{id}, to retrieve all customers and a single customer by id. In the endpoints, we are calling the EnsureCreated method, to be sure that the database and tables are created before retrieving the data.

To retrieve the customer by id, we are using the Find method, that will retrieve the record based on the primary key.

When you run the program and go to the swagger endpoint, you will see something like this:

Seeding data

If you try the customers endpoint, you will see that it doesn't show anything, as expected: we didn't add any customer to the database. We need to seed it with some data: we will use a json file for the initial seed. Create a json file and name it Customer.json. Add the following content to it:

[
    {
      "Id": "BLAUS",
      "Name": "Blauer See Delikatessen",
      "Address": "Forsterstr. 57",
      "City": "Mannheim",
      "Country": "Germany",
      "Phone": "0621-08460"
    },
    {
      "Id": "BOLID",
      "Name": "Bólido Comidas preparadas",
      "Address": "C/ Araquil, 67",
      "City": "Madrid",
      "Country": "Spain",
      "Phone": "(91) 555 22 82"
    },
    {
      "Id": "CHOPS",
      "Name": "Chop-suey Chinese",
      "Address": "Hauptstr. 31",
      "City": "Bern",
      "Country": "Switzerland",
      "Phone": "0452-076545"
    },
    {
      "Id": "FOLKO",
      "Name": "Folk och fä HB",
      "Address": "Åkergatan 24",
      "City": "Bräcke",
      "Country": "Sweden",
      "Phone": "0695-34 67 21"
    },
    {
      "Id": "FRANR",
      "Name": "France restauration",
      "Address": "54, rue Royale",
      "City": "Nantes",
      "Country": "France",
      "Phone": "40.32.21.21"
    },
    {
      "Id": "FURIB",
      "Name": "Furia Bacalhau e Frutos do Mar",
      "Address": "Jardim das rosas n. 32",
      "City": "Lisboa",
      "Country": "Portugal",
      "Phone": "(1) 354-2534"
    },
    {
      "Id": "GOURL",
      "Name": "Gourmet Lanchonetes",
      "Address": "Av. Brasil, 442",
      "City": "Campinas",
      "Country": "Brazil",
      "Phone": "(11) 555-9482"
    },
    {
      "Id": "HANAR",
      "Name": "Hanari Carnes",
      "Address": "Rua do Paço, 67",
      "City": "Rio de Janeiro",
      "Country": "Brazil",
      "Phone": "(21) 555-0091"
    },
    {
      "Id": "ISLAT",
      "Name": "Island Trading",
      "Address": "Garden House Crowther Way",
      "City": "Cowes",
      "Country": "UK",
      "Phone": "(198) 555-8888"
    },
    {
      "Id": "KOENE",
      "Name": "Königlich Essen",
      "Address": "Maubelstr. 90",
      "City": "Brandenburg",
      "Country": "Germany",
      "Phone": "0555-09876"
    },
    {
      "Id": "LAUGB",
      "Name": "Laughing Bacchus Wine Cellars",
      "Address": "2319 Elm St.",
      "City": "Vancouver",
      "Country": "Canada",
      "Phone": "(604) 555-3392"
    },
    {
      "Id": "LILAS",
      "Name": "LILA-Supermercado",
      "Address": "Carrera 52 con Ave. Bolívar #65-98 Llano Largo",
      "City": "Barquisimeto",
      "Country": "Venezuela",
      "Phone": "(9) 331-6954"
    },
    {
      "Id": "LINOD",
      "Name": "LINO-Delicateses",
      "Address": "Ave. 5 de Mayo Porlamar",
      "City": "I. de Margarita",
      "Country": "Venezuela",
      "Phone": "(8) 34-56-12"
    },
    {
      "Id": "MAGAA",
      "Name": "Magazzini Alimentari Riuniti",
      "Address": "Via Ludovico il Moro 22",
      "City": "Bergamo",
      "Country": "Italy",
      "Phone": "035-640230"
    },
    {
      "Id": "MEREP",
      "Name": "Mère Paillarde",
      "Address": "43 rue St. Laurent",
      "City": "Montréal",
      "Country": "Canada",
      "Phone": "(514) 555-8054"
    },
    {
      "Id": "OTTIK",
      "Name": "Ottilies Käseladen",
      "Address": "Mehrheimerstr. 369",
      "City": "Köln",
      "Country": "Germany",
      "Phone": "0221-0644327"
    },
    {
      "Id": "PERIC",
      "Name": "Pericles Comidas clásicas",
      "Address": "Calle Dr. Jorge Cash 321",
      "City": "México D.F.",
      "Country": "Mexico",
      "Phone": "(5) 552-3745"
    },
    {
      "Id": "QUEDE",
      "Name": "Que Delícia",
      "Address": "Rua da Panificadora, 12",
      "City": "Rio de Janeiro",
      "Country": "Brazil",
      "Phone": "(21) 555-4252"
    },
    {
      "Id": "RANCH",
      "Name": "Rancho grande",
      "Address": "Av. del Libertador 900",
      "City": "Buenos Aires",
      "Country": "Argentina",
      "Phone": "(1) 123-5555"
    },
    {
      "Id": "RICAR",
      "Name": "Ricardo Adocicados",
      "Address": "Av. Copacabana, 267",
      "City": "Rio de Janeiro",
      "Country": "Brazil",
      "Phone": "(21) 555-3412"
    },
    {
      "Id": "SIMOB",
      "Name": "Simons bistro",
      "Address": "Vinbæltet 34",
      "City": "Kobenhavn",
      "Country": "Denmark",
      "Phone": "31 12 34 56"
    }
]
JSON

To seed the data, we will override another DbContext method, OnModelCreating and add the following:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    var customersJson = File.ReadAllText("customer.json");
    var customers = JsonSerializer.Deserialize<List<Customer>>(customersJson);
    if (customers is null) return;
    var builder = modelBuilder.Entity<Customer>();
    builder.HasKey(c => c.Id);
    builder.Property(x => x.Id).HasColumnType("TEXT COLLATE NOCASE");
    builder.HasData(customers);
}
C#

The program reads the customer.json file and creates a list of customers. Then we use the the modelBuilder object to configure the Customer entity. The HasData method seeds the entity with data from the customers list, and the HasKey method specifies that the Id property of the Customer entity is the primary key. We set the property Id to be case-insensitive, so we can search independently of the case.

Now we have some data to show, and both methods should work:

The next step is to create the methods for the other operations:

app.MapPost("/customers", async (Customer customer, CustomerDbContext context) =>
{
    context.Customer.Add(customer);
    await context.SaveChangesAsync();
    return Results.Created($"/customers/{customer.Id}", customer);
});

app.MapPut("/customers/{id}", async (string id, Customer customer, CustomerDbContext context) =>
{
    var currentCustomer = await context.Customer.FindAsync(id);
    if (currentCustomer == null)
    {
        return Results.NotFound();
    }

    context.Entry(currentCustomer).CurrentValues.SetValues(customer);
    await context.SaveChangesAsync();
    return Results.NoContent();
});

app.MapDelete("/customers/{id}", async (string id, CustomerDbContext context) =>
{
    var currentCustomer = await context.Customer.FindAsync(id);

    if (currentCustomer == null)
    {
        return Results.NotFound();
    }

    context.Customer.Remove(currentCustomer);
    await context.SaveChangesAsync();
    return Results.NoContent();
});
C#

These three methods will allow us to create, update and delete customers from the database. If you run the code, you will see that the operations appear in the swagger page and all operations work fine:

Adding Logging

We have a functional service, but we can improve it in many ways, like adding logging

using Microsoft.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<CustomerDbContext>();

var app = builder.Build();

var logger = LoggerFactory.Create(config =>
    {
        config.AddConsole();
    }).CreateLogger("CustomerApi");

... 

app.MapGet("/customers", async (CustomerDbContext context) =>
{
    logger.LogInformation("Getting customers...");

    var customers = await context.Customer.ToListAsync();

    logger.LogInformation("Retrieved {Count} customers", customers.Count);

    return Results.Ok(customers);
});
C#

To do this, you must add the package Microsoft.Extensions.Logging and add the namespace to the program. Then, you should create the logger variable, which you can use in the application. If you run the service, you will see this in the console window:

Other improvements

You can add other improvements, like Authorization, Caching or even Controllers to the application. For a quick reference guide on this kind of application, you can take a look at https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-7.0.

Conclusion

As you can see, Minimal APIs in ASP.NET provide a lightweight and simplified approach to building RESTful APIs with minimal ceremony. This article introduced the concept of Minimal APIs and demonstrated how to create RESTful APIs using Minimal APIs in ASP.NET Core.

The article started by explaining the benefits of Minimal APIs, highlighting their concise syntax and reduced boilerplate code, which allows for faster API development and a smaller code footprint. It then provided a step-by-step guide on setting up a new ASP.NET project using the Minimal API template and creating a basic API endpoint that returns weather forecast data. Then, we expanded on the capabilities of Minimal APIs by integrating Swagger, a popular tool for API documentation and testing, providing a user-friendly interface for exploring and testing the API endpoints.

Additionally, the article demonstrated how to implement a more advanced scenario using Minimal APIs and Entity Framework Core. It guided readers through the process of setting up a customer service API that performs CRUD operations on a SQLite database using EF Core, using and seeding the DbContext and difining endpoints for performing the operations on the database.

Overall, Minimal APIs in ASP.NET offer a streamlined approach to building RESTful APIs, allowing developers to quickly create APIs with less boilerplate code. With its simplicity, efficiency and extensibility, Minimal APIs in ASP.NET Core provide a compelling option for developers looking to build modern and scalable APIs.

The code for this article is located at https://github.com/bsonnino/CustomerService

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • May 2025
  • December 2024
  • October 2024
  • August 2024
  • July 2024
  • June 2024
  • November 2023
  • October 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • October 2020
  • September 2020
  • April 2020
  • March 2020
  • January 2020
  • November 2019
  • September 2019
  • August 2019
  • July 2019
  • June 2019
  • April 2019
  • March 2019
  • February 2019
  • January 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • June 2017
  • May 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • February 2016
  • October 2015
  • August 2013
  • May 2013
  • February 2012
  • January 2012
  • April 2011
  • March 2011
  • December 2010
  • November 2009
  • June 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • July 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007
  • July 2007
  • Development
  • English
  • Português
  • Uncategorized
  • Windows

.NET AI Algorithms asp.NET Backup C# Debugging Delphi Dependency Injection Desktop Bridge Desktop icons Entity Framework JSON Linq Mef Minimal API MVVM NTFS Open Source OpenXML OzCode PowerShell Sensors Silverlight Source Code Generators sql server Surface Dial Testing Tools TypeScript UI Unit Testing UWP Visual Studio VS Code WCF WebView2 WinAppSDK Windows Windows 10 Windows Forms Windows Phone WPF XAML Zip

  • Entries RSS
  • Comments RSS
©2025 Bruno Sonnino | Design: Newspaperly WordPress Theme
Menu
  • Home
  • About