Building RESTful APIs in .NET has become more efficient with the introduction of Minimal APIs in .NET 6 and later. Traditionally, developers used ASP.NET Core controllers to create APIs, but Minimal APIs provide a lightweight approach with less boilerplate code. This article will guide you through creating RESTful APIs using Minimal APIs, covering setup, routing, dependency injection, authentication, and best practices.
What Are Minimal APIs?
Minimal APIs in .NET allow developers to build APIs with a streamlined approach, using fewer files and configurations. This results in:
- Faster development due to reduced boilerplate code.
- Improved performance by minimizing overhead.
- Simplified routing and dependency injection.
- Better readability with concise syntax.
Setting Up a Minimal API in .NET
Step 1: Create a New .NET Minimal API Project
Open a terminal or command prompt and run:
mkdir MinimalApiDemo
cd MinimalApiDemo
dotnet new web -o MinimalApiDemo
cd MinimalApiDemo
This command creates a new ASP.NET Core Minimal API project.
Step 2: Install Required Dependencies
Ensure you have the necessary NuGet packages installed:
dotnet add package Microsoft.AspNetCore.OpenApi
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Step 3: Define a Simple Endpoint
Modify Program.cs
to include a simple API endpoint:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/hello", () => "Hello, World!");
app.Run();
Run the application:
dotnet run
Visit http://localhost:5000/hello
in a browser to see the response.
Implementing CRUD Operations with Minimal APIs
Step 4: Define a Model
Create a Product.cs
file:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Step 5: Configure an In-Memory Database
Modify Program.cs
to use Entity Framework Core:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("ProductsDb"));
var app = builder.Build();
app.MapGet("/products", async (AppDbContext db) => await db.Products.ToListAsync());
app.MapPost("/products", async (Product product, AppDbContext db) =>
{
db.Products.Add(product);
await db.SaveChangesAsync();
return Results.Created($"/products/{product.Id}", product);
});
app.Run();
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<Product> Products { get; set; }
}
Run the API and test endpoints with Postman or cURL.
Adding Authentication and Authorization
Step 6: Add JWT Authentication
Add authentication packages:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Modify Program.cs
:
using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://your-auth-server";
options.Audience = "your-api";
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/secure", () => "Secure Data").RequireAuthorization();
app.Run();
Best Practices for Minimal APIs
-
Use dependency injection to manage services efficiently.
-
Enable Swagger for API documentation:
dotnet add package Swashbuckle.AspNetCore
Modify
Program.cs
:builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); app.UseSwagger(); app.UseSwaggerUI();
-
Implement validation using FluentValidation or data annotations.
-
Use logging and exception handling with middleware.
FAQs
1. What are Minimal APIs in .NET?
Minimal APIs provide a lightweight approach to building RESTful APIs with less boilerplate code and improved performance.
2. Can I use authentication with Minimal APIs?
Yes, JWT authentication and other authentication methods can be integrated seamlessly.
3. How do I document Minimal APIs?
Swagger and OpenAPI tools can be used to generate API documentation automatically.
4. Are Minimal APIs suitable for large applications?
Minimal APIs are best for microservices and lightweight applications. For complex systems, controllers might be preferred.
Conclusion
Minimal APIs simplify the development of RESTful APIs in .NET by reducing boilerplate code and improving performance. Whether you're building microservices or lightweight APIs, Minimal APIs offer a modern and efficient approach. Start implementing them today and enhance your .NET development experience!
For more .NET development tips, subscribe to our blog and stay updated with the latest trends!