Work with OpenAPI documents

The Microsoft.AspNetCore.OpenApi package provides built-in support for OpenAPI document generation in ASP.NET Core. The package provides the following features:

  • Support for generating OpenAPI documents at run time and accessing them via an endpoint on the application.
  • Support for "transformer" APIs that allow modifying the generated document.
  • Support for generating multiple OpenAPI documents from a single app.
  • Takes advantage of JSON schema support provided by System.Text.Json.
  • Is compatible with native AoT.

Package installation

Install the Microsoft.AspNetCore.OpenApi package:

Run the following command from the Package Manager Console:

Install-Package Microsoft.AspNetCore.OpenApi -IncludePrerelease

To add support for generating OpenAPI documents at build time, install the Microsoft.Extensions.ApiDescription.Server package:

Run the following command from the Package Manager Console:

Install-Package Microsoft.Extensions.ApiDescription.Server -IncludePrerelease

Configure OpenAPI document generation

The following code:

  • Adds OpenAPI services.
  • Enables the endpoint for viewing the OpenAPI document in JSON format.
var builder = WebApplication.CreateBuilder();

builder.Services.AddOpenApi();

var app = builder.Build();

app.MapOpenApi();

app.MapGet("/", () => "Hello world!");

app.Run();

Launch the app and navigate to https://localhost:<port>/openapi/v1.json to view the generated OpenAPI document.

Including OpenAPI metadata in an ASP.NET web app

ASP.NET collects metadata from the web app's endpoints and uses it to generate an OpenAPI document. In controller-based apps, metadata is collected from attributes like [EndpointDescription], [HttpPost], and [Produces]. In minimal APIs, metadata can be collected from attributes, but may also be set by using extension methods and other strategies, such as returning TypedResults from route handlers. The following table provides an overview of the metadata collected and the strategies for setting it.

Metadata Attribute Extension method Other strategies
summary [EndpointSummary] WithSummary
description [EndpointDescription] WithDescription
tags [Tags] WithTags
operationId [EndpointName] WithName
parameters [FromQuery], [FromRoute], [FromHeader], [FromForm]
parameter description [Description]
requestBody [FromBody] Accepts
responses [Produces], [ProducesProblem] Produces, ProducesProblem TypedResults
Excluding endpoints [ExcludeFromDescription] ExcludeFromDescription

ASP.NET Core does not collect metadata from XML doc comments.

The following sections demonstrate how to include metadata in an app to customize the generated OpenAPI document.

Summary and description

The endpoint summary and description can be set using the [EndpointSummary] and [EndpointDescription] attributes, or in minimal APIs, using the WithSummary and WithDescription extension methods.

The following sample demonstrates the different strategies for setting summaries and descriptions.

Note that the attributes are placed on the delegate method and not on the app.MapGet method.

app.MapGet("/extension-methods", () => "Hello world!")
  .WithSummary("This is a summary.")
  .WithDescription("This is a description.");

app.MapGet("/attributes",
  [EndpointSummary("This is a summary.")]
  [EndpointDescription("This is a description.")]
  () => "Hello world!");

tags

OpenAPI supports specifying tags on each endpoint as a form of categorization. In controller-based apps, the controller name is automatically added as a tag on each of its endpoints, but this can be overridden using the [Tags] attribute. In minimal APIs, tags can be set using either the [Tags] attribute or the WithTags extension method.

The following sample demonstrates the different strategies for setting tags.

app.MapGet("/extension-methods", () => "Hello world!")
  .WithTags("todos", "projects");

app.MapGet("/attributes",
  [Tags("todos", "projects")]
  () => "Hello world!");

operationId

OpenAPI supports an operationId on each endpoint as a unique identifier or name for the operation. In controller-based apps, the operationId can be set using the [EndpointName] attribute. In minimal APIs, the operationId can be set using either the [EndpointName] attribute or the WithName extension method.

The following sample demonstrates the different strategies for setting the operationId.

app.MapGet("/extension-methods", () => "Hello world!")
  .WithName("FromExtensionMethods");

app.MapGet("/attributes",
  [EndpointName("FromAttributes")]
  () => "Hello world!");

parameters

OpenAPI supports annotating path, query string, header, and cookie parameters that are consumed by an API.

The framework infers the types for request parameters automatically based on the signature of the route handler.

The [Description] attribute can be used to provide a description for a parameter.

The follow sample demonstrates how to set a description for a parameter.

app.MapGet("/attributes",
  ([Description("This is a description.")] string name) => "Hello world!");

requestBody

To define the type of inputs transmitted as the request body, configure the properties by using the Accepts extension method to define the object type and content type that are expected by the request handler. In the following example, the endpoint accepts a Todo object in the request body with an expected content-type of application/xml.

app.MapPost("/todos/{id}", (int id, Todo todo) => ...)
  .Accepts<Todo>("application/xml");

In addition to the Accepts extension method, a parameter type can describe its own annotation by implementing the IEndpointParameterMetadataProvider interface. For example, the following Todo type adds an annotation that requires a request body with an application/xml content-type.

public class Todo : IEndpointParameterMetadataProvider
{
    public static void PopulateMetadata(ParameterInfo parameter, EndpointBuilder builder)
    {
        builder.Metadata.Add(new AcceptsMetadata(["application/xml", "text/xml"], typeof(XmlBody)));
    }
}

When no explicit annotation is provided, the framework attempts to determine the default request type if there's a request body parameter in the endpoint handler. The inference uses the following heuristics to produce the annotation:

  • Request body parameters that are read from a form via the [FromForm] attribute are described with the multipart/form-data content-type.
  • All other request body parameters are described with the application/json content-type.
  • The request body is treated as optional if it's nullable or if the AllowEmpty property is set on the FromBody attribute.

Describe response types

OpenAPI supports providing a description of the responses returned from an API. Minimal APIs support three strategies for setting the response type of an endpoint:

The Produces extension method can be used to add Produces metadata to an endpoint. When no parameters are provided, the extension method populates metadata for the targeted type under a 200 status code and an application/json content type.

app.MapGet("/todos", async (TodoDb db) => await db.Todos.ToListAsync())
  .Produces<IList<Todo>>();

Using TypedResults in the implementation of an endpoint's route handler automatically includes the response type metadata for the endpoint. For example, the following code automatically annotates the endpoint with a response under the 200 status code with an application/json content type.

app.MapGet("/todos", async (TodoDb db) =>
{
    var todos = await db.Todos.ToListAsync();
    return TypedResults.Ok(todos);
});

Set responses for ProblemDetails

When setting the response type for endpoints that may return a ProblemDetails response, the ProducesProblem or ProducesValidationProblem extension method or TypedResults.Problem can be used to add the appropriate annotation to the endpoint's metadata.

When there are no explicit annotations provided by one of these strategies, the framework attempts to determine a default response type by examining the signature of the response. This default response is populated under the 200 status code in the OpenAPI definition.

Multiple response types

If an endpoint can return different response types in different scenarios, you can provide metadata in the following ways:

  • Call the Produces extension method multiple times, as shown in the following example:

    app.MapGet("/api/todoitems/{id}", async (int id, TodoDb db) =>
             await db.Todos.FindAsync(id) 
             is Todo todo
             ? Results.Ok(todo) 
             : Results.NotFound())
       .Produces<Todo>(StatusCodes.Status200OK)
       .Produces(StatusCodes.Status404NotFound);
    
  • Use Results<TResult1,TResult2,TResultN> in the signature and TypedResults in the body of the handler, as shown in the following example:

    app.MapGet("/book{id}", Results<Ok<Book>, NotFound> (int id, List<Book> bookList) =>
    {
        return bookList.FirstOrDefault((i) => i.Id == id) is Book book
         ? TypedResults.Ok(book)
         : TypedResults.NotFound();
    });
    

    The Results<TResult1,TResult2,TResultN> union types declare that a route handler returns multiple IResult-implementing concrete types, and any of those types that implement IEndpointMetadataProvider will contribute to the endpoint’s metadata.

    The union types implement implicit cast operators. These operators enable the compiler to automatically convert the types specified in the generic arguments to an instance of the union type. This capability has the added benefit of providing compile-time checking that a route handler only returns the results that it declares it does. Attempting to return a type that isn't declared as one of the generic arguments to Results<TResult1,TResult2,TResultN> results in a compilation error.

Excluding endpoints from the generated document

By default, all endpoints that are defined in an app are documented in the generated OpenAPI file. Minimal APIs support two strategies for excluding a given endpoint from the OpenAPI document, using:

The following sample demonstrates the different strategies for excluding a given endpoint from the generated OpenAPI document.

app.MapGet("/extension-method", () => "Hello world!")
  .ExcludeFromDescription();

app.MapGet("/attributes",
  [ExcludeFromDescription]
  () => "Hello world!");

Options to Customize OpenAPI document generation

The following sections demonstrate how to customize OpenAPI document generation.

Customize the OpenAPI document name

Each OpenAPI document in an app has a unique name. The default document name that is registered is v1.

builder.Services.AddOpenApi(); // Document name is v1

The document name can be modified by passing the name as a parameter to the AddOpenApi call.

builder.Services.AddOpenApi("internal"); // Document name is internal

The document name surfaces in several places in the OpenAPI implementation.

When fetching the generated OpenAPI document, the document name is provided as the documentName parameter argument in the request. The following requests resolve the v1 and internal documents.

GET http://localhost:5000/openapi/v1.json
GET http://localhost:5000/openapi/internal.json

Customize the OpenAPI version of a generated document

By default, OpenAPI document generation creates a document that is compliant with v3.0 of the OpenAPI specification. The following code demonstrates how to modify the default version of the OpenAPI document:

builder.Services.AddOpenApi(options =>
{
    options.OpenApiVersion = OpenApiSpecVersion.OpenApi2_0;
});

Customize the OpenAPI endpoint route

By default, the OpenAPI endpoint registered via a call to MapOpenApi exposes the document at the /openapi/{documentName}.json endpoint. The following code demonstrates how to customize the route at which the OpenAPI document is registered:

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

It's possible, but not recommended, to remove the documentName route parameter from the endpoint route. When the documentName route parameter is removed from the endpoint route, the framework attempts to resolve the document name from the query parameter. Not providing the documentName in either the route or query can result in unexpected behavior.

Customize the OpenAPI endpoint

Because the OpenAPI document is served via a route handler endpoint, any customization that is available to standard minimal endpoints is available to the OpenAPI endpoint.

Limit OpenAPI document access to authorized users

The OpenAPI endpoint doesn't enable any authorization checks by default. However, it's possible to limit access to the OpenAPI document. For example, in the following code, access to the OpenAPI document is limited to those with the tester role:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder();

builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization(o =>
{
    o.AddPolicy("ApiTesterPolicy", b => b.RequireRole("tester"));
});
builder.Services.AddOpenApi();

var app = builder.Build();

app.MapOpenApi()
    .RequireAuthorization("ApiTesterPolicy");

app.MapGet("/", () => "Hello world!");

app.Run();

Cache generated OpenAPI document

The OpenAPI document is regenerated every time a request to the OpenAPI endpoint is sent. Regeneration enables transformers to incorporate dynamic application state into their operation. For example, regenerating a request with details of the HTTP context. When applicable, the OpenAPI document can be cached to avoid executing the document generation pipeline on each HTTP request.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder();

builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(policy => policy.Expire(TimeSpan.FromMinutes(10)));
});
builder.Services.AddOpenApi();

var app = builder.Build();

app.UseOutputCache();

app.MapOpenApi()
    .CacheOutput();

app.MapGet("/", () => "Hello world!");

app.Run();

OpenAPI document transformers

This section demonstrates how to customize OpenAPI documents with transformers.

Customize OpenAPI documents with transformers

Transformers provide an API for modifying the OpenAPI document with user-defined customizations. Transformers are useful for scenarios like:

  • Adding parameters to all operations in a document.
  • Modifying descriptions for parameters or operations.
  • Adding top-level information to the OpenAPI document.

Transformers fall into two categories:

  • Document transformers have access to the entire OpenAPI document. These can be used to make global modifications to the document.
  • Operation transformers apply to each individual operation. Each individual operation is a combination of path and HTTP method. These can be used to modify parameters or responses on endpoints.

Transformers can be registered onto the document by calling the AddDocumentTransformer method on the OpenApiOptions object. The following snippet shows different ways to register transformers onto the document:

  • Register a document transformer using a delegate.
  • Register a document transformer using an instance of IOpenApiDocumentTransformer.
  • Register a document transformer using a DI-activated IOpenApiDocumentTransformer.
  • Register an operation transformer using a delegate.
  • Register an operation transformer using an instance of IOpenApiOperationTransformer.
  • Register an operation transformer using a DI-activated IOpenApiOperationTransformer.
  • Register a schema transformer using a delegate.
  • Register a schema transformer using an instance of IOpenApiSchemaTransformer.
  • Register a schema transformer using a DI-activated IOpenApiSchemaTransformer.
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder();

builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, cancellationToken) 
                             => Task.CompletedTask);
    options.AddDocumentTransformer(new MyDocumentTransformer());
    options.AddDocumentTransformer<MyDocumentTransformer>();
    options.AddOperationTransformer((operation, context, cancellationToken)
                            => Task.CompletedTask);
    options.AddOperationTransformer(new MyOperationTransformer());
    options.AddOperationTransformer<MyOperationTransformer>();
    options.AddSchemaTransformer((schema, context, cancellationToken)
                            => Task.CompletedTask);
    options.AddSchemaTransformer(new MySchemaTransformer());
    options.AddSchemaTransformer<MySchemaTransformer>();
});

var app = builder.Build();

app.MapOpenApi();

app.MapGet("/", () => "Hello world!");

app.Run();

Execution order for transformers

Transformers execute in first-in first-out order based on registration. In the following snippet, the document transformer has access to the modifications made by the operation transformer:

var builder = WebApplication.CreateBuilder();

builder.Services.AddOpenApi(options =>
{
    options.AddOperationTransformer((operation, context, cancellationToken)
                                     => Task.CompletedTask);
    options.AddDocumentTransformer((document, context, cancellationToken)
                                     => Task.CompletedTask);
});

var app = builder.Build();

app.MapOpenApi();

app.MapGet("/", () => "Hello world!");

app.Run();

Use document transformers

Document transformers have access to a context object that includes:

  • The name of the document being modified.
  • The list of ApiDescriptionGroups associated with that document.
  • The IServiceProvider used in document generation.

Document transformers also can mutate the OpenAPI document that is generated. The following example demonstrates a document transformer that adds some information about the API to the OpenAPI document.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;

var builder = WebApplication.CreateBuilder();

builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, cancellationToken) =>
    {
        document.Info = new()
        {
            Title = "Checkout API",
            Version = "v1",
            Description = "API for processing checkouts from cart."
        };
        return Task.CompletedTask;
    });
});

var app = builder.Build();

app.MapOpenApi();

app.MapGet("/", () => "Hello world!");

app.Run();

Service-activated document transformers can utilize instances from DI to modify the app. The following sample demonstrates a document transformer that uses the IAuthenticationSchemeProvider service from the authentication layer. It checks if any JWT bearer-related schemes are registered in the app and adds them to the OpenAPI document's top level:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder();

builder.Services.AddAuthentication().AddJwtBearer();

builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
});

var app = builder.Build();

app.MapOpenApi();

app.MapGet("/", () => "Hello world!");

app.Run();

internal sealed class BearerSecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer
{
    public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
    {
        var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync();
        if (authenticationSchemes.Any(authScheme => authScheme.Name == "Bearer"))
        {
            var requirements = new Dictionary<string, OpenApiSecurityScheme>
            {
                ["Bearer"] = new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer", // "bearer" refers to the header name here
                    In = ParameterLocation.Header,
                    BearerFormat = "Json Web Token"
                }
            };
            document.Components ??= new OpenApiComponents();
            document.Components.SecuritySchemes = requirements;
        }
    }
}

Document transformers are unique to the document instance they're associated with. In the following example, a transformer:

  • Registers authentication-related requirements to the internal document.
  • Leaves the public document unmodified.
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder();

builder.Services.AddAuthentication().AddJwtBearer();

builder.Services.AddOpenApi("internal", options =>
{
    options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
});
builder.Services.AddOpenApi("public");

var app = builder.Build();

app.MapOpenApi();

app.MapGet("/world", () => "Hello world!")
    .WithGroupName("internal");
app.MapGet("/", () => "Hello universe!")
    .WithGroupName("public");

app.Run();

internal sealed class BearerSecuritySchemeTransformer(IAuthenticationSchemeProvider authenticationSchemeProvider) : IOpenApiDocumentTransformer
{
    public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
    {
        var authenticationSchemes = await authenticationSchemeProvider.GetAllSchemesAsync();
        if (authenticationSchemes.Any(authScheme => authScheme.Name == "Bearer"))
        {
            // Add the security scheme at the document level
            var requirements = new Dictionary<string, OpenApiSecurityScheme>
            {
                ["Bearer"] = new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer", // "bearer" refers to the header name here
                    In = ParameterLocation.Header,
                    BearerFormat = "Json Web Token"
                }
            };
            document.Components ??= new OpenApiComponents();
            document.Components.SecuritySchemes = requirements;

            // Apply it as a requirement for all operations
            foreach (var operation in document.Paths.Values.SelectMany(path => path.Operations))
            {
                operation.Value.Security.Add(new OpenApiSecurityRequirement
                {
                    [new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }] = Array.Empty<string>()
                });
            }
        }
    }
}

Use operation transformers

Operations are unique combinations of HTTP paths and methods in an OpenAPI document. Operation transformers are helpful when a modification:

  • Should be made to each endpoint in an app, or
  • Conditionally applied to certain routes.

Operation transformers have access to a context object which contains:

  • The name of the document the operation belongs to.
  • The ApiDescription associated with the operation.
  • The IServiceProvider used in document generation.

For example, the following operation transformer adds 500 as a response status code supported by all operations in the document.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder();

builder.Services.AddAuthentication().AddJwtBearer();

builder.Services.AddOpenApi(options =>
{
    options.AddOperationTransformer((operation, context, cancellationToken) =>
    {
        operation.Responses.Add("500", new OpenApiResponse { Description = "Internal server error" });
        return Task.CompletedTask;
    });
});

var app = builder.Build();

app.MapOpenApi();

app.MapGet("/", () => "Hello world!");

app.Run();

Using the generated OpenAPI document

OpenAPI documents can plug into a wide ecosystem of existing tools for testing, documentation, and local development.

Using Swagger UI for local ad-hoc testing

By default, the Microsoft.AspNetCore.OpenApi package doesn't ship with built-in support for visualizing or interacting with the OpenAPI document. Popular tools for visualizing or interacting with the OpenAPI document include Swagger UI and ReDoc. Swagger UI and ReDoc can be integrated in an app in several ways. Editors such as Visual Studio and VS Code offer extensions and built-in experiences for testing against an OpenAPI document.

The Swashbuckle.AspNetCore.SwaggerUi package provides a bundle of Swagger UI's web assets for use in apps. This package can be used to render a UI for the generated document. To configure this, install the Swashbuckle.AspNetCore.SwaggerUi package.

Enable the swagger-ui middleware with a reference to the OpenAPI route registered earlier. To limit information disclosure and security vulnerability, only enable Swagger UI in development environments.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder();

builder.Services.AddOpenApi();

var app = builder.Build();

app.MapOpenApi();
if (app.Environment.IsDevelopment())
{
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/openapi/v1.json", "v1");
    });

}

app.MapGet("/", () => "Hello world!");

app.Run();

Using Scalar for interactive API documentation

Scalar is an open-source interactive document UI for OpenAPI. Scalar can integrate with the OpenAPI endpoint provided by ASP.NET Core. To configure Scalar, install the Scalar.AspNetCore package.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder();

builder.Services.AddOpenApi();

var app = builder.Build();

app.MapOpenApi();

if (app.Environment.IsDevelopment())
{
    app.MapScalarApiReference();
}

app.MapGet("/", () => "Hello world!");

app.Run();

Lint generated OpenAPI documents with Spectral

Spectral is an open-source OpenAPI document linter. Spectral can be incorporated into an app build to verify the quality of generated OpenAPI documents. Install Spectral according to the package installation directions.

To take advantage of Spectral, install the Microsoft.Extensions.ApiDescription.Server package to enable build-time OpenAPI document generation.

Enable document generation at build time by setting the following properties in your app's .csproj file":

<PropertyGroup>
    <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)</OpenApiDocumentsDirectory>
    <OpenApiGenerateDocuments>true</OpenApiGenerateDocuments>
</PropertyGroup>

Run dotnet build to generate the document.

dotnet build

Create a .spectral.yml file with the following contents.

extends: ["spectral:oas"]

Run spectral lint on the generated file.

spectral lint WebMinOpenApi.json
...

The output shows any issues with the OpenAPI document.

```output
1:1  warning  oas3-api-servers       OpenAPI "servers" must be present and non-empty array.
3:10  warning  info-contact           Info object must have "contact" object.                        info
3:10  warning  info-description       Info "description" must be present and non-empty string.       info
9:13  warning  operation-description  Operation "description" must be present and non-empty string.  paths./.get
9:13  warning  operation-operationId  Operation must have "operationId".                             paths./.get

✖ 5 problems (0 errors, 5 warnings, 0 infos, 0 hints)

Minimal APIs provide built-in support for generating information about endpoints in an app via the Microsoft.AspNetCore.OpenApi package. Exposing the generated OpenAPI definition via a visual UI requires a third-party package. For information about support for OpenAPI in controller-based APIs, see the .NET 9 version of this article.

The following code is generated by the ASP.NET Core minimal web API template and uses OpenAPI:

using Microsoft.AspNetCore.OpenApi;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateTime.Now.AddDays(index),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

app.Run();

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

In the preceding highlighted code:

  • Microsoft.AspNetCore.OpenApi is explained in the next section.
  • AddEndpointsApiExplorer : Configures the app to use the API Explorer to discover and describe endpoints with default annotations. WithOpenApi overrides matching, default annotations generated by the API Explorer with those produced from the Microsoft.AspNetCore.OpenApi package.
  • UseSwaggeradds the Swagger middleware.
  • `UseSwaggerUI` enables an embedded version of the Swagger UI tool.
  • WithName: The IEndpointNameMetadata on the endpoint is used for link generation and is treated as the operation ID in the given endpoint's OpenAPI specification.
  • WithOpenApi is explained later in this article.

Microsoft.AspNetCore.OpenApi NuGet package

ASP.NET Core provides the Microsoft.AspNetCore.OpenApi package to interact with OpenAPI specifications for endpoints. The package acts as a link between the OpenAPI models that are defined in the Microsoft.AspNetCore.OpenApi package and the endpoints that are defined in Minimal APIs. The package provides an API that examines an endpoint's parameters, responses, and metadata to construct an OpenAPI annotation type that is used to describe an endpoint.

Microsoft.AspNetCore.OpenApi is added as a PackageReference to a project file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>    
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.*-*" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
  </ItemGroup>

</Project>

When using Swashbuckle.AspNetCore with Microsoft.AspNetCore.OpenApi, Swashbuckle.AspNetCore 6.4.0 or later must be used. Microsoft.OpenApi 1.4.3 or later must be used to leverage copy constructors in WithOpenApi invocations.

Add OpenAPI annotations to endpoints via WithOpenApi

Calling WithOpenApi on the endpoint adds to the endpoint's metadata. This metadata can be:

  • Consumed in third-party packages like Swashbuckle.AspNetCore.
  • Displayed in the Swagger user interface or in YAML or JSON generated to define the API.
app.MapPost("/todoitems/{id}", async (int id, Todo todo, TodoDb db) =>
{
    todo.Id = id;
    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todo.Id}", todo);
})
.WithOpenApi();

Modify the OpenAPI annotation in WithOpenApi

The WithOpenApi method accepts a function that can be used to modify the OpenAPI annotation. For example, in the following code, a description is added to the first parameter of the endpoint:

app.MapPost("/todo2/{id}", async (int id, Todo todo, TodoDb db) =>
{
    todo.Id = id;
    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todo.Id}", todo);
})
.WithOpenApi(generatedOperation =>
{
    var parameter = generatedOperation.Parameters[0];
    parameter.Description = "The ID associated with the created Todo";
    return generatedOperation;
});

Add operation IDs to OpenAPI

Operation IDs are used to uniquely identify a given endpoint in OpenAPI. The WithName extension method can be used to set the operation ID used for a method.

app.MapGet("/todoitems2", async (TodoDb db) =>
    await db.Todos.ToListAsync())
    .WithName("GetToDoItems");

Alternatively, the OperationId property can be set directly on the OpenAPI annotation.

app.MapGet("/todos", async (TodoDb db) => await db.Todos.ToListAsync())
    .WithOpenApi(operation => new(operation)
    {
        OperationId = "GetTodos"
    });

Add tags to the OpenAPI description

OpenAPI supports using tag objects to categorize operations. These tags are typically used to group operations in the Swagger UI. These tags can be added to an operation by invoking the WithTags extension method on the endpoint with the desired tags.

app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync())
    .WithTags("TodoGroup");

Alternatively, the list of OpenApiTags can be set on the OpenAPI annotation via the WithOpenApi extension method.

app.MapGet("/todos", async (TodoDb db) => await db.Todos.ToListAsync())
    .WithOpenApi(operation => new(operation)
    {
        Tags = new List<OpenApiTag> { new() { Name = "Todos" } }
    });

Add endpoint summary or description

The endpoint summary and description can be added by invoking the WithOpenApi extension method. In the following code, the summaries are set directly on the OpenAPI annotation.

app.MapGet("/todoitems2", async (TodoDb db) => await db.Todos.ToListAsync())
    .WithOpenApi(operation => new(operation)
    {
        Summary = "This is a summary",
        Description = "This is a description"
    });

Exclude OpenAPI description

In the following sample, the /skipme endpoint is excluded from generating an OpenAPI description:

using Microsoft.AspNetCore.OpenApi;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/swag", () => "Hello Swagger!")
    .WithOpenApi();
app.MapGet("/skipme", () => "Skipping Swagger.")
                    .ExcludeFromDescription();

app.Run();

Mark an API as obsolete

To mark an endpoint as obsolete, set the Deprecated property on the OpenAPI annotation.

app.MapGet("/todos", async (TodoDb db) => await db.Todos.ToListAsync())
    .WithOpenApi(operation => new(operation)
    {
        Deprecated = true
    });

Describe response types

OpenAPI supports providing a description of the responses returned from an API. Minimal APIs support three strategies for setting the response type of an endpoint:

The Produces extension method can be used to add Produces metadata to an endpoint. When no parameters are provided, the extension method populates metadata for the targeted type under a 200 status code and an application/json content type.

app
    .MapGet("/todos", async (TodoDb db) => await db.Todos.ToListAsync())
    .Produces<IList<Todo>>();

Using TypedResults in the implementation of an endpoint's route handler automatically includes the response type metadata for the endpoint. For example, the following code automatically annotates the endpoint with a response under the 200 status code with an application/json content type.

app.MapGet("/todos", async (TodoDb db) =>
{
    var todos = await db.Todos.ToListAsync());
    return TypedResults.Ok(todos);
});

Set responses for ProblemDetails

When setting the response type for endpoints that may return a ProblemDetails response, the ProducesProblem extension method, ProducesValidationProblem, or TypedResults.Problem can be used to add the appropriate annotation to the endpoint's metadata. Note that the ProducesProblem and ProducesValidationProblem extension methods can't be used with route groups in .NET 8 and earlier.

When there are no explicit annotations provided by one of the strategies above, the framework attempts to determine a default response type by examining the signature of the response. This default response is populated under the 200 status code in the OpenAPI definition.

Multiple response types

If an endpoint can return different response types in different scenarios, you can provide metadata in the following ways:

  • Call the Produces extension method multiple times, as shown in the following example:

    app.MapGet("/api/todoitems/{id}", async (int id, TodoDb db) =>
             await db.Todos.FindAsync(id) 
             is Todo todo
             ? Results.Ok(todo) 
             : Results.NotFound())
       .Produces<Todo>(StatusCodes.Status200OK)
       .Produces(StatusCodes.Status404NotFound);
    
  • Use Results<TResult1,TResult2,TResultN> in the signature and TypedResults in the body of the handler, as shown in the following example:

    app.MapGet("/book{id}", Results<Ok<Book>, NotFound> (int id, List<Book> bookList) =>
    {
        return bookList.FirstOrDefault((i) => i.Id == id) is Book book
         ? TypedResults.Ok(book)
         : TypedResults.NotFound();
    });
    

    The Results<TResult1,TResult2,TResultN> union types declare that a route handler returns multiple IResult-implementing concrete types, and any of those types that implement IEndpointMetadataProvider will contribute to the endpoint’s metadata.

    The union types implement implicit cast operators. These operators enable the compiler to automatically convert the types specified in the generic arguments to an instance of the union type. This capability has the added benefit of providing compile-time checking that a route handler only returns the results that it declares it does. Attempting to return a type that isn't declared as one of the generic arguments to Results<TResult1,TResult2,TResultN> results in a compilation error.

Describe request body and parameters

In addition to describing the types that are returned by an endpoint, OpenAPI also supports annotating the inputs that are consumed by an API. These inputs fall into two categories:

  • Parameters that appear in the path, query string, headers, or cookies
  • Data transmitted as part of the request body

The framework infers the types for request parameters in the path, query, and header string automatically based on the signature of the route handler.

To define the type of inputs transmitted as the request body, configure the properties by using the Accepts extension method to define the object type and content type that are expected by the request handler. In the following example, the endpoint accepts a Todo object in the request body with an expected content-type of application/xml.

app.MapPost("/todos/{id}", (int id, Todo todo) => ...)
  .Accepts<Todo>("application/xml");

In addition to the Accepts extension method, A parameter type can describe its own annotation by implementing the IEndpointParameterMetadataProvider interface. For example, the following Todo type adds an annotation that requires a request body with an application/xml content-type.

public class Todo : IEndpointParameterMetadataProvider
{
    public static void PopulateMetadata(ParameterInfo parameter, EndpointBuilder builder)
    {
        builder.Metadata.Add(new ConsumesAttribute(typeof(Todo), isOptional: false, "application/xml"));
    }
}

When no explicit annotation is provided, the framework attempts to determine the default request type if there's a request body parameter in the endpoint handler. The inference uses the following heuristics to produce the annotation:

  • Request body parameters that are read from a form via the [FromForm] attribute are described with the multipart/form-data content-type.
  • All other request body parameters are described with the application/json content-type.
  • The request body is treated as optional if it's nullable or if the AllowEmpty property is set on the FromBody attribute.

Support API versioning

Minimal APIs support API versioning via the Asp.Versioning.Http package. Examples of configuring versioning with minimal APIs can be found in the API versioning repo.

ASP.NET Core OpenAPI source code on GitHub

Additional Resources

A minimal API app can describe the OpenAPI specification for route handlers using Swashbuckle.

For information about support for OpenAPI in controller-based APIs, see the .NET 9 version of this article.

The following code is a typical ASP.NET Core app with OpenAPI support:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = builder.Environment.ApplicationName,
                               Version = "v1" });
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger(); // UseSwaggerUI Protected by if (env.IsDevelopment())
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",
                                    $"{builder.Environment.ApplicationName} v1"));
}

app.MapGet("/swag", () => "Hello Swagger!");

app.Run();

Exclude OpenAPI description

In the following sample, the /skipme endpoint is excluded from generating an OpenAPI description:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(); // UseSwaggerUI Protected by if (env.IsDevelopment())
}

app.MapGet("/swag", () => "Hello Swagger!");
app.MapGet("/skipme", () => "Skipping Swagger.")
                    .ExcludeFromDescription();

app.Run();

Describe response types

The following example uses the built-in result types to customize the response:

app.MapGet("/api/todoitems/{id}", async (int id, TodoDb db) =>
         await db.Todos.FindAsync(id) 
         is Todo todo
         ? Results.Ok(todo) 
         : Results.NotFound())
   .Produces<Todo>(StatusCodes.Status200OK)
   .Produces(StatusCodes.Status404NotFound);

Add operation ids to OpenAPI

app.MapGet("/todoitems2", async (TodoDb db) =>
    await db.Todos.ToListAsync())
    .WithName("GetToDoItems");

Add tags to the OpenAPI description

The following code uses an OpenAPI grouping tag:

app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync())
    .WithTags("TodoGroup");