Minimal APIs, Endpoints & Swagger Masterclass
๐ Covered in this chapter:
Minimal APIs ยท MapGet/Post/Put/Delete ยท Route Parameters ยท Query Parameters ยท Request Body ยท Results Helper ยท Status Codes ยท Swagger UI
Welcome to Phase 12 (Chapter 33): C# ASP.NET Core Minimal APIs, Endpoints, Routing & Swagger Masterclass! Minimal APIs (.NET 6+) allow building lightweight HTTP endpoints with minimal boilerplate directly in Program.cs without controllers or action methods. In this chapter, we create GET, POST, PUT, DELETE endpoints, handle route parameters, query strings, request bodies, status codes, validation, error handling, and Swagger documentation.
1Creating Minimal API Endpoints (GET, POST, PUT, DELETE)
C# โ Complete Minimal API Example
โถ Run in Compiler
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
// In-memory product store
var products = new List<Product>
{
new Product(1, "Laptop", 75000m),
new Product(2, "Mouse", 1200m)
};
// GET all products
app.MapGet("/api/products", () => Results.Ok(products));
// GET single product by ID
app.MapGet("/api/products/{id:int}", (int id) =>
{
var product = products.FirstOrDefault(p => p.Id == id);
return product is not null ? Results.Ok(product) : Results.NotFound($"Product {id} not found.");
});
// POST create product
app.MapPost("/api/products", (Product newProduct) =>
{
products.Add(newProduct);
return Results.Created($"/api/products/{newProduct.Id}", newProduct);
});
// DELETE product
app.MapDelete("/api/products/{id:int}", (int id) =>
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product is null) return Results.NotFound();
products.Remove(product);
return Results.NoContent();
});
app.Run();
// Record model
public record Product(int Id, string Name, decimal Price);
2Technical FAQs
Q1: When should I use Minimal APIs vs Controller-Based APIs?
Use Minimal APIs for simple microservices, serverless functions, or prototypes where you want minimal ceremony. Use Controller-Based APIs for large enterprise applications requiring model binding, filters, action results, and structured routing.