Dear fellow geeks, If you’re working on or trying to explore details info regarding .NET 9 / want to create blazing-fast, lightweight APIs without the junk code, you’re in the right place.
.NET 9 Minimal APIs are a game-changer for building modern web services, and today, I’m sharing practical .NET 9 Minimal APIs with examples to get you started.
Whether you’re a C# veteran or just exploring .NET 9’s shiny new features (released November 2024), this guide will walk you through hands-on code to create, secure, and document APIs like a pro. Let’s jump in!
Table of Contents
ToggleWhy .NET 9 Minimal APIs Are Awesome
Minimal APIs in .NET 9 let you build RESTful APIs with less code than traditional MVC controllers, making them perfect for microservices, startups, or quick prototypes. With .NET 9’s performance boosts (think faster startup and lower memory usage), minimal APIs are ideal for cloud-native apps, especially on Azure. Plus, they’re super easy to set up, so you can focus on coding features, not ceremony.
In this post, I’ll share .NET 9 Minimal APIs with examples covering:
- A basic GET API
- CRUD operations with dependency injection
- JWT authentication
- Swagger documentation
Ready to code? Let’s do this!
Example 1: Basic GET API with .NET 9 Minimal APIs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Sample product data
var products = new[]
{
new { Id = 1, Name = "Laptop", Price = 999.99 },
new { Id = 2, Name = "Phone", Price = 499.99 }
};
// GET endpoint
app.MapGet("/products", () => Results.Ok(products));
app.Run();
Let’s start simple. Here’s how to create a minimal API that returns a list of products.
What’s happening here?
- We create a web app with WebApplication.CreateBuilder.
- Define a GET endpoint at /products that returns JSON-serialized products.
- Run the app, and you’re live!
Why it’s cool: This is way leaner than setting up a full MVC controller. You can test it by navigating to http://localhost:5000/products (or your port) and see the JSON output. Perfect for quick prototypes!
Pro Tip: Use this for simple APIs or hackathons where speed matters.
Example 2: CRUD Operations with Dependency Injection
Now, let’s build a todo API with CRUD (Create, Read, Update, Delete) operations using an in-memory store and dependency injection.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
var builder = WebApplication.CreateBuilder(args);
// Register in-memory store
builder.Services.AddSingleton<List<Todo>>();
var app = builder.Build();
// GET all todos
app.MapGet("/todos", (List<Todo> todos) => Results.Ok(todos));
// POST a new todo
app.MapPost("/todos", async (HttpContext http, List<Todo> todos) =>
{
var todo = await http.Request.ReadFromJsonAsync<Todo>();
if (todo == null) return Results.BadRequest();
todos.Add(todo);
return Results.Created($"/todos/{todo.Id}", todo);
});
// DELETE a todo
app.MapDelete("/todos/{id}", (int id, List<Todo> todos) =>
{
var todo = todos.Find(t => t.Id == id);
if (todo == null) return Results.NotFound();
todos.Remove(todo);
return Results.NoContent();
});
app.Run();
record Todo(int Id, string Title, bool IsComplete);
What’s happening?
- We register a List<Todo> as a singleton for in-memory storage.
- Define endpoints for GET (/todos), POST (/todos), and DELETE (/todos/{id}).
- Use Results to return proper HTTP status codes (e.g., 201 Created, 404 NotFound).
Why it’s useful: This shows how to handle real-world CRUD operations with minimal APIs. You can extend it with a database like Azure Cosmos DB for production apps.
Try it out: Use Postman to POST a todo ({ “Id”: 1, “Title”: “Learn .NET 9”, “IsComplete”: false }) and GET the list to see it in action.
Example 3: Securing Your API with JWT Authentication
Security is key for production APIs. Let’s add JWT authentication to protect an endpoint.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add JWT authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "your-issuer",
ValidAudience = "your-audience",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("your-secure-key-32-chars-long"))
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// Protected endpoint
app.MapGet("/secure", (HttpContext http) =>
{
var user = http.User.Identity?.Name ?? "Anonymous";
return Results.Ok($"Hello, {user}!");
}).RequireAuthorization();
app.Run();
What’s happening?
- We configure JWT authentication with a secret key.
- Add the [Authorize] equivalent (RequireAuthorization()) to protect the /secure endpoint.
- Only requests with a valid JWT token can access it.
Why it’s important: Security is non-negotiable. This example shows how to lock down your .NET 9 minimal APIs for real-world use.
Next steps: Generate a JWT token (e.g., via an auth server or tool like jwt.io) and test it in Postman with the Authorization: Bearer <token> header.
Why Choose .NET 9 Minimal APIs?
Here’s why .NET 9 Minimal APIs with examples like these are worth your time:
- Performance: .NET 9’s optimizations make minimal APIs faster than ever, ideal for microservices.
- Simplicity: Less code means faster development and easier maintenance.
- Azure Integration: Deploy to Azure App Service or Functions with seamless CI/CD.
- Community Buzz: Developers on Reddit and Stack Overflow are raving about minimal APIs for their elegance and speed.
Tips for Success with .NET 9 Minimal APIs
- Start Small: Use the basic GET example to prototype, then scale to CRUD or auth.
- Deploy to Azure: Try Azure App Service for easy hosting. Check out my guide on deploying .NET 9 minimal APIs to Azure for steps.
- Monitor Performance: Use .NET 9’s AOT compilation for even faster startups (more on that in my AOT guide).
- Engage the Community: Share your APIs on X or /r/dotnet to get feedback.
FAQs About .NET 9 Minimal APIs with Examples
Q: How do I add a database to .NET 9 minimal APIs?
A: Use Entity Framework Core with Azure SQL or Cosmos DB. Replace the in-memory List<Todo> in Example 2 with a DbContext.
Q: Are minimal APIs production-ready?
A: Absolutely! With authentication (Example 3) and proper error handling, they’re great for production, especially for microservices.
Q: How do I test .NET 9 minimal APIs?
A: Use Postman or Swagger (Example 4) for manual testing, and xUnit for automated tests.
Wrapping Up
.NET 9 Minimal APIs are a fantastic way to build fast, scalable APIs with minimal fuss. From simple GET endpoints to secure, documented APIs, these .NET 9 Minimal APIs with examples show how easy it is to get started. Whether you’re deploying to Azure or building a startup MVP, minimal APIs have you covered.
Got questions or want more examples? Drop a comment below or ping me on X! And if you’re curious about .NET 9’s other features, check out detailed post on same from Microsoft.
Happy coding, and let’s make some awesome APIs with .NET 9! Cheers 🙂

1 thought on “.NET 9 Minimal APIs with Examples: Build Super Fast, Lightweight APIs in Minutes”