How to Build a CRUD API with .NET Minimal APIs and Swagger

How to Build a CRUD API with .NET Minimal APIs and Swagger

·

4 min read

Developing a well-documented CRUD API in .NET just got easier with Minimal APIs and Swagger. In this guide, learn how to build a fast, lightweight CRUD API and generate interactive API docs using these new .NET tools.

Why Build CRUD APIs with .NET Minimal APIs?

.NET Minimal APIs introduced in .NET 6 provide a streamlined way to build web APIs with minimal code and configuration. Here are some benefits:

  • Reduce boilerplate code - No Startup.cs or controllers required

  • Improve developer productivity - Get up and running fast

  • Clean, lightweight code - Route handlers defined as lambdas

  • Easy to maintain - Less code means fewer bugs

For rapidly building CRUD APIs, Minimal APIs are perfect to reduce development overhead.

Adding Swagger Documentation to Your .NET API

While Minimal APIs speed up development, Swagger makes your API easy to use for consumers. Swagger docs enable developers to:

  • Interactively explore API endpoints

  • Understand parameters and models

  • View example requests/responses

  • Generate client SDKs

By integrating Swagger into your .NET API, you create a professional, self-documenting developer experience.

Mainly three things to do in the Project

Setting up the SQL Database

First, we need a database to store our superhero records. For .NET web projects, SQL Server is a popular relational database choice. We'll use SSMS (SQL Server Management Studio) to create and manage a SQL Server database instance locally.

SSMS provides a graphical interface to easily create databases, tables, views, and other objects in SQL Server. We can connect to the built-in LocalDB instance and use T-SQL (Transact-SQL) statements to define our schema.

For our API, we'll create a simple table called SuperHeroes with columns like Id, Name, Alias to store key superhero data. This gives our API a persistent data store that we can query and update from our API logic.

Creating the .NET Core API

Next, we'll use .NET Minimal APIs to implement a CRUD (create, read, update, delete) API over our SuperHeroes data. Minimal APIs introduced in .NET 6 provide a lightweight way to build web APIs without a lot of ceremony.

We simply scaffold a console app project and define each CRUD route inline in our Program class. For example, a GET route to fetch all heroes and a POST route to create new heroes. Minimal configuration and boilerplate code is needed to get a functioning API.

This allows us to focus on the API logic rather than infrastructure code. We can quickly build out each API endpoint as the core functionality.

Integrating Entity Framework Core

Now that we have our API routes defined, we need to hook them up to our SQL database. This is where Entity Framework Core comes in.

EF Core provides an object-relational mapper (ORM) that allows us to query and persist .NET objects to a database. We define entity classes that match our table structure and a DbContext class that handles connections and CRUD operations.

Inside our route handlers, we can then use the db context to retrieve or save hero entities. EF Core translates this simple object code into optimized SQL queries under the hood.

So with very little data access code, our API is now persisting information in the SQL database!

Step-by-Step: Building a CRUD API with .NET and Swagger

  1. Create a .NET 7 console app

Image description

  1. un-check the use of controller

  2. install the required Nuget Packages

  3. configure Swagger

     builder.Services.AddSwaggerGen(); 
     builder.Services.AddEndpointsApiExplorer();
    
     var app = builder.Build();
    
     if(builder.Environment.IsDevelopment()) 
      {
      app.UseSwagger();
      app.UseSwaggerUI();
      }
    
  4. Add class "SuperHero" and its DBContext with connection string

public class SuperHero { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string HeroName { get; set; } }

public class DataContext : DbContext
 { 
  public DataContext(DbContextOptions<DataContext> options) : base(options) { } 

  public DbSet<SuperHero> SuperHeroes => Set<SuperHero>(); 
}
"ConnectionStrings": { "DefaultConnection": "server=localhost\\sqlexpress; database=minimaldb; trusted_connection=true;TrustServerCertificate=true" }
  1. Initiate Migration and Update the Database

     dotnet ef migrations add Initial
    

    then,

     dotnet ef database update
    

    this will create DB in SSMS

    Image description

start to Add all you CRUD operation through Minimal APIs Route handlers defined as lambdas

In Program.cs we can define our CRUD routes:

app.MapGet("/products", () => { // get all products logic });

app.MapGet("/products/{id}", (int id) => { // get product by id logic });

app.MapPost("/products", (Product product) => { // create product logic });

app.MapPut("/products/{id}", (int id, Product product) => { // update product logic });

app.MapDelete("/products/{id}", (int id) => { // delete product logic });

Conclusion

Using .NET Minimal APIs, Swagger, and EF Core together provides a streamlined way to build a documented data-driven API. Minimal APIs reduce code, Swagger handles docs, and EF Core connects to the database.

By leveraging these .NET technologies, we can build production-ready web APIs faster with less boilerplate code getting in the way. The entire stack works elegantly together to create robust APIs with great developer experience.

P.S : akhil2kv/MinimalAPI-SuperHero: this project is just deomstrate the power of Minimal API usage with Swagger(openAPI) (github.com)