Minimal APIs
Minimal APIs let you build HTTP endpoints with very little ceremony: you map a URL pattern and an HTTP method directly to a C# function. They are the default style for new APIs in .NET 9 (dotnet new webapi) and are what most of this course uses.
Mapping endpoints
WebApplication has a Map… method for each common HTTP method:
| Method | Typical meaning |
|---|---|
app.MapGet(pattern, handler) |
Read data |
app.MapPost(pattern, handler) |
Create something |
app.MapPut(pattern, handler) |
Replace something |
app.MapPatch(pattern, handler) |
Partially update something |
app.MapDelete(pattern, handler) |
Delete something |
app.MapMethods(pattern, ["HEAD", "OPTIONS"], handler) |
Any other methods |
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var todos = new List<Todo>
{
new(1, "Learn minimal APIs", false),
new(2, "Buy coffee", true),
};
app.MapGet("/todos", () => todos);
app.MapGet("/todos/{id:int}", (int id) =>
todos.FirstOrDefault(t => t.Id == id) is { } todo
? Results.Ok(todo)
: Results.NotFound());
app.MapPost("/todos", (Todo todo) =>
{
todos.Add(todo);
return Results.Created(quot;/todos/{todo.Id}", todo);
});
app.MapDelete("/todos/{id:int}", (int id) =>
todos.RemoveAll(t => t.Id == id) > 0 ? Results.NoContent() : Results.NotFound());
app.Run();
record Todo(int Id, string Title, bool IsDone);Note: A plain
List<T>shared by all requests is not thread-safe. It is fine for a demo, but real apps use a database or a concurrent collection.
Here is what calling those endpoints looks like:
$ curl -s localhost:5000/todos
$ curl -s localhost:5000/todos/2
$ curl -s -X POST localhost:5000/todos -H "Content-Type: application/json" -d '{"id":3,"title":"Write tests","isDone":false}'
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/todos/99[{"id":1,"title":"Learn minimal APIs","isDone":false},{"id":2,"title":"Buy coffee","isDone":true}]
{"id":2,"title":"Buy coffee","isDone":true}
{"id":3,"title":"Write tests","isDone":false}
404
Notice that the C# properties Id, Title and IsDone became id, title and isDone: ASP.NET Core serializes JSON with camelCase names by default (the "web defaults" of System.Text.Json).
What a handler can return
| Handler returns | Response |
|---|---|
string |
200, text/plain, the string as the body |
Any other object (Todo, List<Todo>, anonymous type) |
200, application/json, the object serialized |
IResult (Results.Ok, Results.NotFound, …) |
Whatever the result describes: status, headers, body |
Task<T> / ValueTask<T> |
The same rules, after awaiting |
void / Task |
200 with an empty body |
You can reproduce the JSON part with System.Text.Json directly — this is exactly the serializer ASP.NET Core uses:
using System;
using System.Collections.Generic;
using System.Text.Json;
var webDefaults = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var todos = new List<Todo> { new(1, "Learn minimal APIs", false), new(2, "Buy coffee", true) };
Console.WriteLine(JsonSerializer.Serialize(todos, webDefaults));
// Anonymous types work too
var summary = new { Total = todos.Count, Done = todos.FindAll(t => t.IsDone).Count };
Console.WriteLine(JsonSerializer.Serialize(summary, webDefaults));
// Without web defaults the names keep their C# casing
Console.WriteLine(JsonSerializer.Serialize(todos[0]));
record Todo(int Id, string Title, bool IsDone);[{"id":1,"title":"Learn minimal APIs","isDone":false},{"id":2,"title":"Buy coffee","isDone":true}]
{"total":2,"done":1}
{"Id":1,"Title":"Learn minimal APIs","IsDone":false}
Handlers: lambdas, local functions or methods
The handler is just a delegate, so you can use whichever form keeps your code readable:
app.MapGet("/ping", () => "pong"); // lambda
string Hello(string name) => quot;Hello, {name}"; // local function
app.MapGet("/hello/{name}", Hello);
app.MapGet("/stats", TodoHandlers.GetStats); // static method
static class TodoHandlers
{
public static object GetStats() => new { Version = 1 };
}Handlers can also be async:
app.MapGet("/slow", async () =>
{
await Task.Delay(100);
return new { Message = "Done waiting" };
});Grouping endpoints with MapGroup
When many endpoints share a prefix (and often the same settings such as authorization), put them in a route group:
var todosApi = app.MapGroup("/api/todos");
todosApi.MapGet("/", () => todos); // GET /api/todos
todosApi.MapGet("/{id:int}", (int id) => todos.Find(t => t.Id == id)); // GET /api/todos/1
todosApi.MapPost("/", (Todo t) => { todos.Add(t); return Results.Created(quot;/api/todos/{t.Id}", t); });Settings applied to a group — .RequireAuthorization(), .WithTags("Todos"), endpoint filters — apply to every endpoint inside it.
How parameters are filled
Minimal APIs inspect your handler's parameters and fill each one automatically. Here is the idea in plain C# using reflection — the framework does this once at startup and generates fast code for it:
using System;
using System.Collections.Generic;
using System.Reflection;
Func<int, string, string> handler = (int id, string format) => quot;Todo {id} as {format}";
// Values that arrived with a request: route value "id", query string "format"
var routeValues = new Dictionary<string, string> { ["id"] = "42" };
var query = new Dictionary<string, string> { ["format"] = "json" };
var handlerArgs = new List<object>();
foreach (ParameterInfo p in handler.Method.GetParameters())
{
string raw = routeValues.TryGetValue(p.Name!, out var r) ? r : query[p.Name!];
object value = Convert.ChangeType(raw, p.ParameterType);
Console.WriteLine(quot;{p.Name} ({p.ParameterType.Name}) <- \"{raw}\"");
handlerArgs.Add(value);
}
Console.WriteLine(handler.DynamicInvoke(handlerArgs.ToArray()));id (Int32) <- "42"
format (String) <- "json"
Todo 42 as json
The next lessons look at each source in turn: route values, query strings, headers, the JSON body and services from dependency injection.
Minimal APIs or controllers?
| Minimal APIs | Controllers (MVC) | |
|---|---|---|
| Code style | Lambdas / methods mapped in code | Classes with action methods and attributes |
| Boilerplate | Very little | More structure |
| Performance | Slightly faster, AOT-friendly | Very fast |
| Best for | New APIs, microservices | Large existing codebases, apps that also use views |
Both are fully supported, and they can live in the same app.
Test yourself
Which call handles HTTP DELETE requests to /todos/5?
- app.MapGet("/todos/{id}", …)
- app.MapRemove("/todos/{id}", …)
- app.MapDelete("/todos/{id}", …)
- app.Delete("/todos/{id}", …)
A handler returns new Todo(1, "Test", false). What does the client receive?
Todo { Id = 1 }as text- JSON
{"id":1,"title":"Test","isDone":false}with status 200 - Status 204 No Content
- XML
What is app.MapGroup("/api/todos") useful for?
- Sharing a URL prefix and settings across several endpoints
- Running endpoints in parallel
- Creating a database table
- Grouping log messages