How to Build a CRUD API with .NET Minimal APIs and Swagger
Tags: dotnet, csharp, api
Published: 2023-11-11 18:21:27

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

2. **un-check the use of controller**
3. install the required Nuget Packages 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9wk006tos95fc26drcml.png)
4.configure Swagger 
`            builder.Services.AddSwaggerGen();
            builder.Services.AddEndpointsApiExplorer();

            var app = builder.Build();

            if(builder.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }`

5. 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"
  }`

6. Initiate Migration and Update the Database
`dotnet ef migrations add Initial`
then, `dotnet ef database update`
this will create DB in SSMS
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kd5ecl1nliksyo3dr0ba.png)
7. 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
});``