First minimal API
First minimal API
A Minimal API is an ASP.NET Core endpoint defined with a route handler rather than a controller class. HTTP methods and paths identify operations; results select status codes and representations. Minimal does not mean validation, security or testing are optional.
A resource is a thing a client addresses, such as a book. Use GET for retrieval, not for modifying state. A response contract includes status, headers and body shape. A DTO (data transfer object) explicitly represents the public fields rather than exposing internal entities. Returning a string normally produces text; returning an object normally produces JSON. TypedResults produces concrete result types. Results<T1,T2> lets a handler explicitly declare alternative result types. This lesson uses a fixed synthetic inventory and never persists customer data.
Baseline: .NET 10 / C# 14. Each code block is an independent static example with a companion Web SDK project. Read the endpoint registration and client checks first; the surrounding host harness is repeated for standalone use. Expected observations are reasoned, not executed. Run only in a clean, isolated local environment with an approved SDK; no launch profile, external network or real data. The OpenAPI package example additionally requires approved restore.
Return an inventory DTO
Inspect the JSON fields instead of depending on whitespace or object property order.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/books/2", () => new BookDto(2, "Map Atlas"));using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var response = await client.GetAsync("/books/2", deadline.Token); using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(deadline.Token)); Console.WriteLine((int)response.StatusCode); Console.WriteLine(response.Content.Headers.ContentType!.MediaType); Console.WriteLine(body.RootElement.GetProperty("title").GetString());}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}record BookDto(int Id, string Title);The serializer uses web JSON defaults; the DTO fields become id and title.
Expected observation (reasoned, not executed):
200application/jsonMap AtlasReturn a typed 200 or 404
A constrained path handles numeric IDs; the handler decides whether the resource exists.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/books/{id:int}", Results<Ok<BookDto>, NotFound> (int id) => id == 2 ? TypedResults.Ok(new BookDto(2, "Map Atlas")) : TypedResults.NotFound());using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; foreach (int id in new[] { 2, 9 }) { using var response = await client.GetAsync($"/books/{id}", deadline.Token); Console.WriteLine((int)response.StatusCode); }}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}record BookDto(int Id, string Title);A valid ID need not identify an existing resource. The union restricts the declared outcomes.
Expected observation (reasoned, not executed):
200404Inspect method mismatch
A mapped GET route does not automatically accept POST.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/catalog", () => "read only");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var response = await client.PostAsync("/catalog", new StringContent(""), deadline.Token); Console.WriteLine((int)response.StatusCode); Console.WriteLine(response.Content.Headers.Allow.Contains("GET") ? "GET allowed" : "GET missing");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}The path exists but does not support the method. HTTP 405 includes an Allow header; HttpClient exposes it through content headers.
Expected observation (reasoned, not executed):
405GET allowedCommon mistakes and design boundaries
An empty 200 response is not a substitute for a meaningful 404. Do not update data through GET, expose internal entity fields accidentally, or assume a typed result replaces integration tests. A small route handler can delegate business rules to separately tested services.
Apply your understanding
Design GET /books/7 for an existing book with title River Guide and GET /books/8 for a missing book. Specify the status, content type and body contract.
Complete the linked manual practice and knowledge check. The examples are not automated ByteMind assessments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
First minimal API — knowledge check
Apply the lesson concepts to the following scenarios.
Which method should retrieve a book without changing its state?
A numeric book ID does not exist. What result fits?
What is a DTO useful for?
What does a handler returning Results<Ok<BookDto>, NotFound> declare?
A GET-only path receives POST. What is the expected status?