What is Minimal API in .NET?
Minimal API is a lightweight way to build HTTP APIs in .NET (introduced in .NET 6).
It allows you to create REST APIs with less code, without Controllers, Startup class, or complex structure.
👉 Best for:
- Microservices
- Small REST APIs
- Backend for Angular/React apps
🔥 Traditional API vs Minimal API
| Traditional ASP.NET Core | Minimal API |
|---|---|
| Uses Controllers | No Controllers |
| Uses Startup.cs | No Startup.cs |
| More boilerplate code | Very less code |
| Better for large apps | Best for small/medium APIs |
Step by Step Implementation
- Create .NET Core API based Project
- Go into Program.cs
- Write only this code
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
- Run the application
Step by Step CRUD Operation (Minimal API)
Install Swagger Package: Swashbuckle.AspNetCore
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
List<Student> students = new()
{
new Student(1, "Shiva", 22),
new Student(2, "Rahul", 23)
};
// GET all students
app.MapGet("/students", () => students);
// GET by ID
app.MapGet("/students/{id}", (int id) =>
{
var student = students.FirstOrDefault(s => s.Id == id);
return student is not null ? Results.Ok(student) : Results.NotFound();
});
// POST
app.MapPost("/students", (Student student) =>
{
students.Add(student);
return Results.Created($"/students/{student.Id}", student);
});
// PUT
app.MapPut("/students/{id}", (int id, Student updatedStudent) =>
{
var student = students.FirstOrDefault(s => s.Id == id);
if (student is null)
return Results.NotFound();
students.Remove(student);
students.Add(updatedStudent);
return Results.Ok(updatedStudent);
});
// DELETE
app.MapDelete("/students/{id}", (int id) =>
{
var student = students.FirstOrDefault(s => s.Id == id);
if (student is null)
return Results.NotFound();
students.Remove(student);
return Results.Ok();
});
app.Run();
public record Student(int Id, string Name, int Age);

0 Comments
POST Answer of Questions and ASK to Doubt