DEV Community

Akhil K V
Akhil K V

Posted on

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

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.

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
    Image description
    4.configure Swagger
    ` builder.Services.AddSwaggerGen();
    builder.Services.AddEndpointsApiExplorer();

        var app = builder.Build();
    
        if(builder.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }`
    
  3. 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
  2. start to Add all you CRUD operation through Minimal APIs Route handlers defined as lambdas

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

Top comments (0)