Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FROZEN: Add build-time OpenAPI generation doc #33359

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aspnetcore/fundamentals/openapi/aspnetcore-openapi.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ 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 via the `UseTransformer` call on the `OpenApiOptions` object. The following snippet shows different ways to register transformers onto the document:
Transformers can be registered onto the document via the `AddDocumentTransformer` call 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`.
Expand Down
100 changes: 100 additions & 0 deletions aspnetcore/fundamentals/openapi/buildtime-openapi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
---
title: Generate OpenAPI documents at build time
author: captainsafia
description: Learn how to generate OpenAPI documents in your application's build step
ms.author: safia
monikerRange: '>= aspnetcore-6.0'
ms.custom: mvc
ms.date: 8/13/2024
uid: fundamentals/openapi/buildtime-openapi
---

# Generate OpenAPI documents at build-time
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Rick-Anderson @tdykstra This definitely needs some massaging for prose and formatting but the material covered is true to what I think we should cover. Feel free to modify this branch as you see fit.


In a typical web applications, OpenAPI documents are generated at run-time and served via an HTTP request to the application server.

In some scenarios, it is helpful to generate the OpenAPI document during the application's build step. These scenarios including:

- Generating OpenAPI documentation that is committed into source control
- Generating OpenAPI documentation that is used for spec-based integration testing
- Generating OpenAPI documentation that is served statically from the web server

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

### [Visual Studio](#tab/visual-studio)

Run the following command from the **Package Manager Console**:

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

### [.NET CLI](#tab/net-cli)

Run the following command in the directory that contains the project file:

```dotnetcli
dotnet add package Microsoft.Extensions.ApiDescription.Server --prerelease
```
---

Upon installation, this package will automatically generate the Open API document(s) associated with the application during build and populate them into the application's output directory.

```cli
$ dotnet build
$ cat bin/Debub/net9.0/{ProjectName}.json
```

## Customizing build-time document generation

### Modifying the output directory of the generated Open API file

By default, the generated OpenAPI document will be emitted to the application's output directory. To modify the location of the emitted file, set the target path in the `OpenApiDocumentsDirectory` property.

```xml
<PropertyGroup>
<OpenApiDocumentsDirectory>./</OpenApiDocumentsDirectory>
</PropertyGroup>
```

The value of `OpenApiDocumentsDirectory` is resolved relative to the project file. Using the `./` value above will emit the OpenAPI document in the same directory as the project file.

### Modifying the output file name

By default, the generated OpenAPI document will have the same name as the application's project file. To modify the name of the emitted file, set the `--file-name` argument in the `OpenApiGenerateDocumentsOptions` property.

```xml
<PropertyGroup>
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
```

### Selecting the OpenAPI document to generate

Some applications may be configured to emit multiple OpenAPI documents, for various versions of an API or to distinguish between public and internal APIs. By default, the build-time document generator will emit files for all documents that are configured in an application. To only emit for a single document name, set the `--document-name` argument in the `OpenApiGenerateDocumentsOptions` property.

```xml
<PropertyGroup>
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
```

## Customizing run-time behavior during build-time document generation

Under the hood, build-time OpenAPI document generation functions by launching the application's entrypoint with an inert server implementation. This is a requirement to produce accurate OpenAPI documents since all information in the OpenAPI document cannot be statically analyzed. Because the application's entrypoint is invoked, any logic in the applications' startup will be invoked. This includes code that injects services into the DI container or reads from configuration. In some scenarios, it's necessary to restrict the codepaths that will run when the application's entry point is being invoked from build-time document generation. These scenarios include:

- Not reading from certain configuration strings
- Not registering database-related services

In order to restrict these codepaths from being invoked by the build-time generation pipeline, they can be conditioned behind a check of the entry assembly like so:

```csharp
using System.Reflection;

var builder = WebApplication.CreateBuilder();

if (Assembly.GetEntryAssembly()?.GetName().Name != "GetDocument.Insider")
{
builders.Services.AddDefaults();
}
```
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary

builder.Services.AddOpenApi(options =>
{
options.UseTransformer((document, context, cancellationToken) =>
options.AddDocumentTransformer((document, context, cancellationToken) =>
{
document.Info = new()
{
Expand Down Expand Up @@ -91,7 +91,7 @@ internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary

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

var app = builder.Build();
Expand Down Expand Up @@ -141,7 +141,7 @@ public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransf

builder.Services.AddOpenApi(options =>
{
options.UseOperationTransformer((operation, context, cancellationToken) =>
options.AddOperationTransformer((operation, context, cancellationToken) =>
{
operation.Responses.Add("500", new OpenApiResponse { Description = "Internal server error" });
return Task.CompletedTask;
Expand Down Expand Up @@ -172,7 +172,7 @@ public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransf

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

Expand Down Expand Up @@ -360,11 +360,11 @@ public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransf

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

Expand Down Expand Up @@ -396,9 +396,9 @@ public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerC

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OpenApiDocumentsDirectory>./</OpenApiDocumentsDirectory>
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
</PropertyGroup>

<PropertyGroup>
Expand All @@ -12,14 +14,14 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-preview.5.24257.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0-preview.5.24257.1" />
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="9.0.0-preview.5.24257.1">
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-rc.1.24414.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0-rc.1.24414.3" />
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="9.0.0-rc.1.24414.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Scalar.AspNetCore" Version="1.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="6.7.0" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
}
}
}
},
"x-aspnetcore-id": "14ccb7f6-1846-48e4-aeaf-c760aadda7c3"
}
}
}
},
"components": { },
"tags": [
{
"name": "GetDocument.Insider"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"sdk": {
"version": "9.0.100-rc.1.24414.13"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"openapi": "3.0.1",
"info": {
"title": "GetDocument.Insider | v1",
"version": "1.0.0"
},
"paths": {
"/": {
"get": {
"tags": [
"GetDocument.Insider"
],
"responses": {
"200": {
"description": "OK",
"content": {
"text/plain": {
"schema": {
"type": "string"
}
}
}
}
}
}
}
},
"components": { },
"tags": [
{
"name": "GetDocument.Insider"
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ OpenAPI transformers support modifying the OpenAPI document, operations within t
Previously, the following APIs were available for registering transformers:

```csharp
OpenApiOptions UseTransformer(Func<OpenApiDocument, OpenApiDocumentTransformerContext, CancellationToken, Task> transformer)
OpenApiOptions UseTransformer(IOpenApiDocumentTransformer transformer)
OpenApiOptions UseTransformer<IOpenApiDocumentTransformer>()
OpenApiOptions AddDocumentTransformer(Func<OpenApiDocument, OpenApiDocumentTransformerContext, CancellationToken, Task> transformer)
OpenApiOptions AddDocumentTransformer(IOpenApiDocumentTransformer transformer)
OpenApiOptions AddDocumentTransformer<IOpenApiDocumentTransformer>()
OpenApiOptions UseSchemaTransformer(Func<OpenApiSchema, OpenApiSchemaTransformerContext, CancellationToken, Task>)
OpenApiOptions UseOperationTransformer(Func<OpenApiOperation, OpenApiOperationTransformerContext, CancellationToken, Task>)
OpenApiOptions AddOperationTransformer(Func<OpenApiOperation, OpenApiOperationTransformerContext, CancellationToken, Task>)
```

The new API set is as follows:
Expand Down
2 changes: 2 additions & 0 deletions aspnetcore/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,8 @@ items:
uid: fundamentals/openapi/overview
- name: Work with OpenAPI documents
uid: fundamentals/openapi/aspnetcore-openapi
- name: Generate OpenAPI documents at build-time
uid: fundamentals/openapi/buildtime-openapi
- name: OpenAPI tools
uid: fundamentals/openapi/openapi-tools
- name: Swagger / NSWag
Expand Down
Loading