loading experience

ASP.NET Core

OpenAPI 3.1 in ASP.NET Core 10: documenting your APIs

An OpenAPI document generated from code, XML comments as descriptions and output in YAML too.

OpenAPI 3.1 in ASP.NET Core 10: documenting your APIs

An OpenAPI document describes your APIs in a way people and tools can read: automatically generated clients, tests, gateways, developer portals. ASP.NET Core generates it straight from the code.

The document is generated from code and always stays in sync.
The document is generated from code and always stays in sync.

Minimal configuration

builder.Services.AddOpenApi();

var app = builder.Build();
app.MapOpenApi();          // /openapi/v1.json

In .NET 10 the document follows the OpenAPI 3.1 specification, aligned with JSON Schema: nullable types and schemas are described more precisely.

Descriptions from XML comments

By enabling XML documentation generation in the project, the <summary> comments on methods and types become descriptions in the OpenAPI document.

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
/// <summary>Returns a product given its code.</summary>
/// <param name="code">Item code, for example ABC-123.</param>
static async Task<Results<Ok<Product>, NotFound>> FindProduct(string code, ICatalog catalog) =>
    await catalog.FindAsync(code) is { } p ? TypedResults.Ok(p) : TypedResults.NotFound();

app.MapGet("/products/{code}", FindProduct);

In YAML too

app.MapOpenApi("/openapi/{documentName}.yaml");

Exposing it safely

The document reveals the structure of your APIs: in production consider publishing it only to authenticated users or only in the development environment. For a browsable interface, add dedicated tools such as Scalar or Swagger UI.

Comments (0)

No comments yet.

Leave a comment