ASP.NET Core cookbook · Beginner

Generate OpenAPI documents with Microsoft.AspNetCore.OpenApi

API consumers need an accurate, up-to-date contract with auth requirements and examples.

Create a free account to save this page, take notes and track your progress. Sign in

Approach

Call AddOpenApi() and MapOpenApi() to serve the document generated from your endpoints. Describe endpoints with names, summaries and TypedResults, and add a document transformer for security schemes.

Solution

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, ct) =>
    {
        document.Info.Title = "Orders API";
        document.Info.Version = "v1";
        return Task.CompletedTask;
    });
});
var app = builder.Build();

if (app.Environment.IsDevelopment() || app.Configuration.GetValue<bool>("Docs:Public"))
{
    app.MapOpenApi();                                   // GET /openapi/v1.json
}

app.MapGet("/api/orders/{id:int}", (int id) => TypedResults.Ok(new OrderDto(id, "paid")))
    .WithName("GetOrder")
    .WithSummary("Get an order by ID")
    .WithDescription("Returns 404 when the order doesn't exist or belongs to another customer.")
    .Produces(StatusCodes.Status404NotFound);
app.Run();

public record OrderDto(int Id, string Status);

Pitfalls

  • Publishing internal admin endpoints in the public document; exclude them with .ExcludeFromDescription().
  • Anonymous types in responses, which produce poorly named schemas; use records.
  • Documentation that drifts because it's written by hand instead of generated.

Variations

  • Generate the document at build time (Microsoft.Extensions.ApiDescription.Server) and diff it in CI.
  • Serve a UI such as Scalar or Swagger UI pointing at /openapi/v1.json.

Further reading: Generate OpenAPI documents

Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/aspnetcore-openapi

More ASP.NET Core recipes

Was this page helpful?