Building a minimal API with ASP.NET Core
Course contents (16 lessons)
- The type system
- Records, structs and value equality
- Interfaces and abstract classes
- Generics and constraints
- Delegates, events and lambdas
- Querying and matching data
- LINQ in depth: deferred execution, grouping and joins
- IEnumerable versus IQueryable
- Pattern matching in modern C#
- Async and await: how Task really works
- Async patterns: cancellation, timeouts and async streams
- Application structure
- Dependency injection and service lifetimes
- Configuration, options and logging
- Data and web
- Entity Framework Core basics: DbContext, migrations and queries
- Building a minimal API with ASP.NET Core
- Unit testing with xunit
- Performance and the final project
- Performance basics: Span of T and fewer allocations
- Final project: a notes API with EF Core, DI and logging
An API in one file
ASP.NET Core minimal APIs let you build an HTTP service with very little ceremony. There are no controllers and no base classes. You map a URL and an HTTP method to a function. It is a good fit for small services and for learning how web APIs work, and it is fully capable for large ones as well.
Create the project with dotnet new web -n TodoApi. Open Program.cs and replace the content with the code below. Run it with dotnet run and use the URL it prints.
using System.Collections.Concurrent;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<TodoStore>();
var app = builder.Build();
app.MapGet("/", () => "Todo API is running. Try /todos");
var todos = app.MapGroup("/todos");
todos.MapGet("/", (TodoStore store, bool? done) =>
{
var items = store.All();
if (done is not null)
{
items = items.Where(t => t.IsDone == done).ToList();
}
return TypedResults.Ok(items);
});
todos.MapGet("/{id:int}", (int id, TodoStore store) =>
store.Find(id) is Todo todo
? Results.Ok(todo)
: Results.NotFound(new { message = $"Todo {id} was not found." }));
todos.MapPost("/", (CreateTodo input, TodoStore store) =>
{
if (string.IsNullOrWhiteSpace(input.Title) || input.Title.Length > 100)
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["title"] = ["Title is required and must be at most 100 characters."]
});
}
Todo created = store.Add(input.Title.Trim());
return Results.Created($"/todos/{created.Id}", created);
});
todos.MapPut("/{id:int}/done", (int id, TodoStore store) =>
store.MarkDone(id) ? Results.NoContent() : Results.NotFound());
todos.MapDelete("/{id:int}", (int id, TodoStore store) =>
store.Remove(id) ? Results.NoContent() : Results.NotFound());
app.Run();
record Todo(int Id, string Title, bool IsDone);
record CreateTodo(string Title);
class TodoStore
{
private readonly ConcurrentDictionary<int, Todo> _items = new();
private int _lastId;
public List<Todo> All() => _items.Values.OrderBy(t => t.Id).ToList();
public Todo? Find(int id) => _items.TryGetValue(id, out var t) ? t : null;
public Todo Add(string title)
{
var todo = new Todo(Interlocked.Increment(ref _lastId), title, false);
_items[todo.Id] = todo;
return todo;
}
public bool MarkDone(int id)
{
if (!_items.TryGetValue(id, out var existing)) return false;
_items[id] = existing with { IsDone = true };
return true;
}
public bool Remove(int id) => _items.TryRemove(id, out _);
}
Walking through it
WebApplication.CreateBuilder builds the same host you met in the configuration lesson, with the web server added. Services are registered on builder.Services, and then builder.Build() gives an app where you map endpoints. app.Run() starts listening.
Each MapGet, MapPost and so on takes a route and a handler. The framework looks at the handler's parameters and decides where each comes from. That is called parameter binding, and the rules are simple.
- A name that matches a route placeholder, like
idin/{id:int}, comes from the route. The:intconstraint also stops/todos/abcfrom matching. - A simple type that is not in the route, like
bool? done, comes from the query string:/todos?done=true. - A complex type on a POST or PUT, like
CreateTodo, comes from the JSON body. - A registered service, like
TodoStore, comes from dependency injection.
MapGroup("/todos") gives a shared prefix. You can also attach shared behaviour to a group, such as authorisation or filters.
The return values set the HTTP status. Results.Ok is 200, Results.Created is 201 with a Location header, Results.NoContent is 204, and Results.NotFound is 404. TypedResults returns the same results with concrete types, which helps OpenAPI documentation and tests. Anything else you return, like a string or an object, is written as 200 with JSON.
The POST handler validates by hand. Results.ValidationProblem returns a 400 response in the standard problem-details format. For larger APIs, a validation library or the built-in validation support in recent ASP.NET Core versions saves repetitive code, but the principle stays: never trust the body.
The store is a singleton because it holds the data in memory, so it uses a ConcurrentDictionary and Interlocked.Increment to be safe when requests overlap. Data disappears when the app restarts. In the final project we replace this with EF Core.
Trying it
With the app running, send requests from a second terminal. Replace the port with the one printed by dotnet run:
curl -X POST http://localhost:5000/todos -H "Content-Type: application/json" -d "{\"title\":\"Write lesson\"}"
curl http://localhost:5000/todos
curl -X PUT http://localhost:5000/todos/1/done
curl "http://localhost:5000/todos?done=true"
Common mistakes
- Putting business logic in the endpoint lambdas. Handlers should read the request, call a service, and shape the response.
- Returning entities directly and exposing fields that should stay private. Return DTO records.
- Forgetting to return the right status code. A 200 with an error message in the body breaks clients.
- Not handling invalid bodies. A missing or malformed JSON body gives a 400, but empty fields pass through unless you check them.
- Ignoring the cancellation token. Add a
CancellationTokenparameter to long handlers and pass it down.
Try it yourself
- Add a
PUT /todos/{id}endpoint that renames a todo, with the same title validation. - Add a
searchquery parameter toGET /todosthat filters by title. - Call
builder.Services.AddOpenApi()andapp.MapOpenApi()in development to see the generated description of your API.
using System.Collections.Concurrent;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<TodoStore>();
var app = builder.Build();
app.MapGet("/", () => "Todo API is running. Try /todos");
var todos = app.MapGroup("/todos");
todos.MapGet("/", (TodoStore store, bool? done) =>
{
var items = store.All();
if (done is not null)
{
items = items.Where(t => t.IsDone == done).ToList();
}
return TypedResults.Ok(items);
});
todos.MapGet("/{id:int}", (int id, TodoStore store) =>
store.Find(id) is Todo todo
? Results.Ok(todo)
: Results.NotFound(new { message = $"Todo {id} was not found." }));
todos.MapPost("/", (CreateTodo input, TodoStore store) =>
{
if (string.IsNullOrWhiteSpace(input.Title) || input.Title.Length > 100)
{
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["title"] = ["Title is required and must be at most 100 characters."]
});
}
Todo created = store.Add(input.Title.Trim());
return Results.Created($"/todos/{created.Id}", created);
});
todos.MapPut("/{id:int}/done", (int id, TodoStore store) =>
store.MarkDone(id) ? Results.NoContent() : Results.NotFound());
todos.MapDelete("/{id:int}", (int id, TodoStore store) =>
store.Remove(id) ? Results.NoContent() : Results.NotFound());
app.Run();
record Todo(int Id, string Title, bool IsDone);
record CreateTodo(string Title);
class TodoStore
{
private readonly ConcurrentDictionary<int, Todo> _items = new();
private int _lastId;
public List<Todo> All() => _items.Values.OrderBy(t => t.Id).ToList();
public Todo? Find(int id) => _items.TryGetValue(id, out var t) ? t : null;
public Todo Add(string title)
{
var todo = new Todo(Interlocked.Increment(ref _lastId), title, false);
_items[todo.Id] = todo;
return todo;
}
public bool MarkDone(int id)
{
if (!_items.TryGetValue(id, out var existing)) return false;
_items[id] = existing with { IsDone = true };
return true;
}
public bool Remove(int id) => _items.TryRemove(id, out _);
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account