Minimal APIs are a lightweight way to build HTTP APIs in .NET with minimal ceremony. Introduced in .NET 6, they focus on simplicity and performance.
Minimal APIs eliminate the complexity of traditional ASP.NET Core MVC. No controllers, no heavy configuration.
Why Choose Minimal APIs?
- Efficiency: Achieve more with less code.
- High Performance: Lightweight and optimized for fast execution.
- Beginner-Friendly: Minimal APIs are easy to learn and implement, especially for those new to .NET.
- Flexible & Scalable: Don't be fooled by the name, Minimal APIs can power everything from microservices to enterprise-grade systems.
Build a Minimal API Project from Scratch
Let's walk through creating a Minimal API using the .NET CLI or Visual Studio.
Step 1. Create the Project
dotnet new web -n MinimalApiDemo
cd MinimalApiDemo
start MinimalApiDemo.sln
Step 2. Add Your First Endpoint
A typical start can always, a hello world project.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello from Minimal API!");
app.Run();
Run the app
dotnet run
Navigate to https://localhost:5001/ and you'll see the response.
"Hello from Minimal API!"
Step 3. Adding models and services
Now, let's go ahead and make our project more like a real project, starting by.
Create the Product model Models/Product.cs.
namespace ProductApi.Models
{
public class Product
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
}
Create a file: Services/IProductService.cs.
using ProductApi.Models;
namespace ProductApi.Services
{
public interface IProductService
{
IEnumerable<Product> GetAll();
Product? GetById(Guid id);
Product Create(Product product);
bool Delete(Guid id);
Product? Update(Guid id, Product updatedProduct);
}
}
Now create the implementation in Services/ProductService.cs.
using ProductApi.Models;
namespace ProductApi.Services
{
public class ProductService : IProductService
{
private readonly List<Product> _products = new();
public IEnumerable<Product> GetAll() => _products;
public Product? GetById(Guid id) =>
_products.FirstOrDefault(p => p.Id == id);
public Product Create(Product product)
{
_products.Add(product);
return product;
}
public bool Delete(Guid id)
{
var product = GetById(id);
if (product == null) return false;
_products.Remove(product);
return true;
}
public Product? Update(Guid id, Product updatedProduct)
{
var product = GetById(id);
if (product == null) return null;
product.Name = updatedProduct.Name;
product.Price = updatedProduct.Price;
return product;
}
}
}
Join the conversation! Your thoughts help the community grow.