Skip to content

Commit 90ee5ed

Browse files
committed
Add build-time OpenAPI generation docs
1 parent 41a2203 commit 90ee5ed

File tree

14 files changed

+164
-21
lines changed

14 files changed

+164
-21
lines changed

aspnetcore/fundamentals/openapi/aspnetcore-openapi.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ Transformers fall into two categories:
427427
* Document transformers have access to the entire OpenAPI document. These can be used to make global modifications to the document.
428428
* 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.
429429

430-
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:
430+
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:
431431

432432
* Register a document transformer using a delegate.
433433
* Register a document transformer using an instance of `IOpenApiDocumentTransformer`.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
---
2+
title: Generate OpenAPI documents at build time
3+
author: captainsafia
4+
description: Learn how to generate OpenAPI documents in your application's build step
5+
ms.author: safia
6+
monikerRange: '>= aspnetcore-6.0'
7+
ms.custom: mvc
8+
ms.date: 8/13/2024
9+
uid: fundamentals/openapi/buildtime-openapi
10+
---
11+
12+
# Generate OpenAPI documents at build-time
13+
14+
In a typical web applications, OpenAPI documents are generated at run-time and served via an HTTP request to the application server.
15+
16+
In some scenarios, it is helpful to generate the OpenAPI document during the application's build step. These scenarios including:
17+
18+
- Generating OpenAPI documentation that is committed into source control
19+
- Generating OpenAPI documentation that is used for spec-based integration testing
20+
- Generating OpenAPI documentation that is served statically from the web server
21+
22+
To add support for generating OpenAPI documents at build time, install the `Microsoft.Extensions.ApiDescription.Server` package:
23+
24+
### [Visual Studio](#tab/visual-studio)
25+
26+
Run the following command from the **Package Manager Console**:
27+
28+
```powershell
29+
Install-Package Microsoft.Extensions.ApiDescription.Server -IncludePrerelease
30+
```
31+
32+
### [.NET CLI](#tab/net-cli)
33+
34+
Run the following command in the directory that contains the project file:
35+
36+
```dotnetcli
37+
dotnet add package Microsoft.Extensions.ApiDescription.Server --prerelease
38+
```
39+
---
40+
41+
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.
42+
43+
```cli
44+
$ dotnet build
45+
$ cat bin/Debub/net9.0/{ProjectName}.json
46+
```
47+
48+
## Customizing build-time document generation
49+
50+
### Modifying the output directory of the generated Open API file
51+
52+
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.
53+
54+
```xml
55+
<PropertyGroup>
56+
<OpenApiDocumentsDirectory>./</OpenApiDocumentsDirectory>
57+
</PropertyGroup>
58+
```
59+
60+
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.
61+
62+
### Modifying the output file name
63+
64+
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.
65+
66+
```xml
67+
<PropertyGroup>
68+
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
69+
</PropertyGroup>
70+
```
71+
72+
### Selecting the OpenAPI document to generate
73+
74+
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.
75+
76+
```xml
77+
<PropertyGroup>
78+
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions>
79+
</PropertyGroup>
80+
```
81+
82+
## Customizing run-time behavior during build-time document generation
83+
84+
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:
85+
86+
- Not reading from certain configuration strings
87+
- Not registering database-related services
88+
89+
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:
90+
91+
```csharp
92+
using System.Reflection;
93+
94+
var builder = WebApplication.CreateBuilder();
95+
96+
if (Assembly.GetEntryAssembly()?.GetName().Name != "GetDocument.Insider")
97+
{
98+
builders.Services.AddDefaults();
99+
}
100+
```

aspnetcore/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/Program.cs renamed to aspnetcore/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary
5555

5656
builder.Services.AddOpenApi(options =>
5757
{
58-
options.UseTransformer((document, context, cancellationToken) =>
58+
options.AddDocumentTransformer((document, context, cancellationToken) =>
5959
{
6060
document.Info = new()
6161
{
@@ -91,7 +91,7 @@ internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary
9191

9292
builder.Services.AddOpenApi(options =>
9393
{
94-
options.UseTransformer<BearerSecuritySchemeTransformer>();
94+
options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
9595
});
9696

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

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

173173
builder.Services.AddOpenApi("internal", options =>
174174
{
175-
options.UseTransformer<BearerSecuritySchemeTransformer>();
175+
options.AddDocumentTransformer<BearerSecuritySchemeTransformer>();
176176
});
177177
builder.Services.AddOpenApi("public");
178178

@@ -360,11 +360,11 @@ public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransf
360360

361361
builder.Services.AddOpenApi(options =>
362362
{
363-
options.UseTransformer((document, context, cancellationToken)
363+
options.AddDocumentTransformer((document, context, cancellationToken)
364364
=> Task.CompletedTask);
365-
options.UseTransformer(new MyDocumentTransformer());
366-
options.UseTransformer<MyDocumentTransformer>();
367-
options.UseOperationTransformer((operation, context, cancellationToken)
365+
options.AddDocumentTransformer(new MyDocumentTransformer());
366+
options.AddDocumentTransformer<MyDocumentTransformer>();
367+
options.AddOperationTransformer((operation, context, cancellationToken)
368368
=> Task.CompletedTask);
369369
});
370370

@@ -396,9 +396,9 @@ public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerC
396396

397397
builder.Services.AddOpenApi(options =>
398398
{
399-
options.UseOperationTransformer((operation, context, cancellationToken)
399+
options.AddOperationTransformer((operation, context, cancellationToken)
400400
=> Task.CompletedTask);
401-
options.UseTransformer((document, context, cancellationToken)
401+
options.AddDocumentTransformer((document, context, cancellationToken)
402402
=> Task.CompletedTask);
403403
});
404404

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
<TargetFramework>net9.0</TargetFramework>
55
<Nullable>enable</Nullable>
66
<ImplicitUsings>enable</ImplicitUsings>
7+
<OpenApiDocumentsDirectory>./</OpenApiDocumentsDirectory>
8+
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
79
</PropertyGroup>
810

911
<PropertyGroup>
@@ -12,14 +14,14 @@
1214
</PropertyGroup>
1315

1416
<ItemGroup>
15-
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-preview.5.24257.1" />
16-
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0-preview.5.24257.1" />
17-
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="9.0.0-preview.5.24257.1">
17+
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-rc.1.24414.3" />
18+
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0-rc.1.24414.3" />
19+
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="9.0.0-rc.1.24414.3">
1820
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
1921
<PrivateAssets>all</PrivateAssets>
2022
</PackageReference>
2123
<PackageReference Include="Scalar.AspNetCore" Version="1.0.1" />
22-
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="6.5.0" />
24+
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUi" Version="6.7.0" />
2325
</ItemGroup>
2426

2527
</Project>

aspnetcore/fundamentals/minimal-apis/9.0-samples/WebMinOpenApi/WebMinOpenApi.json renamed to aspnetcore/fundamentals/openapi/samples/9.x/WebMinOpenApi/WebMinOpenApi.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@
2121
}
2222
}
2323
}
24-
},
25-
"x-aspnetcore-id": "14ccb7f6-1846-48e4-aeaf-c760aadda7c3"
24+
}
2625
}
2726
}
2827
},
28+
"components": { },
2929
"tags": [
3030
{
3131
"name": "GetDocument.Insider"
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"sdk": {
3+
"version": "9.0.100-rc.1.24414.13"
4+
}
5+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
{
2+
"openapi": "3.0.1",
3+
"info": {
4+
"title": "GetDocument.Insider | v1",
5+
"version": "1.0.0"
6+
},
7+
"paths": {
8+
"/": {
9+
"get": {
10+
"tags": [
11+
"GetDocument.Insider"
12+
],
13+
"responses": {
14+
"200": {
15+
"description": "OK",
16+
"content": {
17+
"text/plain": {
18+
"schema": {
19+
"type": "string"
20+
}
21+
}
22+
}
23+
}
24+
}
25+
}
26+
}
27+
},
28+
"components": { },
29+
"tags": [
30+
{
31+
"name": "GetDocument.Insider"
32+
}
33+
]
34+
}

0 commit comments

Comments
 (0)