Building REST APIs with ASP.NET Core 10
Build a small REST API with ASP.NET Core minimal APIs, route groups, typed results, validation, and OpenAPI support.
Part 1: What You Will Learn
Build a small REST API with ASP.NET Core minimal APIs, route groups, typed results, validation, and OpenAPI support.
- Create endpoints with `MapGet`, `MapPost`, and route parameters.
- Group related endpoints under a common route prefix.
- Return correct HTTP results such as 200, 201, 400, and 404.
- Enable OpenAPI metadata for API exploration and tooling.
Project setup: Create an ASP.NET Core Empty or Web API project targeting .NET 10. Replace Program.cs with the example below.
Part 2: Topic-Specific Working Example
The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapOpenApi();
List<TodoItem> todos =
[
new(1, "Learn minimal APIs", false),
new(2, "Build a REST endpoint", false)
];
RouteGroupBuilder group = app.MapGroup("/api/todos");
group.MapGet("/", () => Results.Ok(todos));
group.MapGet("/{id:int}", (int id) =>
{
TodoItem? item = todos.FirstOrDefault(t => t.Id == id);
return item is null
? Results.NotFound()
: Results.Ok(item);
});
group.MapPost("/", (CreateTodoRequest request) =>
{
if (string.IsNullOrWhiteSpace(request.Title))
return Results.BadRequest("Title is required.");
TodoItem item = new(
todos.Count + 1,
request.Title.Trim(),
false);
todos.Add(item);
return Results.Created($"/api/todos/{item.Id}", item);
});
app.Run();
public record TodoItem(int Id, string Title, bool IsDone);
public record CreateTodoRequest(string Title);Part 3: How the Code Works
- `MapGroup('/api/todos')` gives all related endpoints a common prefix.
- `Results.NotFound()` and `Results.BadRequest()` communicate failure using appropriate HTTP status codes.
- `Results.Created()` returns HTTP 201 and supplies the new resource location.
- `AddOpenApi()` and `MapOpenApi()` expose OpenAPI information for clients and development tooling.
Part 4: Mini Project & Practice
Mini project: add PUT `/api/todos/{id}` and DELETE `/api/todos/{id}` endpoints. Test the API from Visual Studio's HTTP file or another API client.
Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.
When you are comfortable with this lesson, continue to Lesson 31.
C# in Visual Studio 2026
📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.
View on Amazon Kindle Edition