Skip to content

Commit 04b6934

Browse files
authored
Edit pass on 'Generate OpenAPI documents' (#36147)
1 parent 7dfda7e commit 04b6934

File tree

1 file changed

+68
-62
lines changed

1 file changed

+68
-62
lines changed

aspnetcore/fundamentals/openapi/aspnetcore-openapi.md

Lines changed: 68 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
---
22
title: Generate OpenAPI documents
33
author: captainsafia
4-
description: Learn how to generate and customize OpenAPI documents in an ASP.NET Core app
4+
description: Learn how to generate and customize OpenAPI documents in an ASP.NET Core app.
55
ms.author: safia
66
monikerRange: '>= aspnetcore-6.0'
77
ms.custom: mvc
8-
ms.date: 09/22/2025
8+
ms.date: 09/23/2025
99
uid: fundamentals/openapi/aspnetcore-openapi
1010
---
1111
# Generate OpenAPI documents
@@ -14,53 +14,53 @@ uid: fundamentals/openapi/aspnetcore-openapi
1414

1515
The [`Microsoft.AspNetCore.OpenApi`](https://www.nuget.org/packages/Microsoft.AspNetCore.OpenApi) package provides built-in support for OpenAPI document generation in ASP.NET Core. The package provides the following features:
1616

17-
* Support for generating [OpenAPI version 3.1] documents.
18-
* Support for [JSON Schema draft 2020-12].
17+
* Support for generating [OpenAPI version 3.1](https://spec.openapis.org/oas/v3.1.1.html) documents.
18+
* Support for [JSON Schema draft 2020-12](https://json-schema.org/specification-links#2020-12).
1919
* Support for generating OpenAPI documents at run time and accessing them via an endpoint on the app.
2020
* Support for "transformer" APIs that allow modifying the generated document.
2121
* Support for generating multiple OpenAPI documents from a single app.
22-
* Takes advantage of JSON schema support provided by [`System.Text.Json`](/dotnet/api/system.text.json).
23-
* Is compatible with native AoT.
22+
* Takes advantage of JSON schema support provided by <xref:System.Text.Json?displayProperty=fullName>.
23+
* Compatible with native AoT.
2424

25-
[OpenAPI version 3.1]: https://spec.openapis.org/oas/v3.1.1.html
26-
[JSON Schema draft 2020-12]: https://json-schema.org/specification-links#2020-12
27-
28-
The default OpenAPI version for generated documents is`3.1`. The version can be changed by explicitly setting the [OpenApiVersion](/dotnet/api/microsoft.aspnetcore.openapi.openapioptions.openapiversion) property of the [OpenApiOptions](/dotnet/api/microsoft.aspnetcore.openapi.openapioptions) in the `configureOptions` delegate parameter of [AddOpenApi](/dotnet/api/microsoft.extensions.dependencyinjection.openapiservicecollectionextensions.addopenapi):
25+
The default OpenAPI version for generated documents is 3.1. The version can be changed by explicitly setting the <xref:Microsoft.AspNetCore.OpenApi.OpenApiOptions.OpenApiVersion%2A> property of the <xref:Microsoft.AspNetCore.OpenApi.OpenApiOptions> in the `configureOptions` delegate parameter of <xref:Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi%2A>:
2926

3027
```csharp
3128
builder.Services.AddOpenApi(options =>
3229
{
33-
// Specify the OpenAPI version to use.
30+
// Specify the OpenAPI version to use
3431
options.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0;
3532
});
3633
```
3734

3835
When generating the OpenAPI document at build time, the OpenAPI version can be selected by setting the `--openapi-version` in the `OpenApiGenerateDocumentsOptions` MSBuild item.
3936

4037
```xml
41-
<!-- Configure build-time OpenAPI generation to produce an OpenAPI 3.1 document. -->
42-
<OpenApiGenerateDocumentsOptions>--openapi-version OpenApi3_1</OpenApiGenerateDocumentsOptions>
38+
<!-- Configure build-time OpenAPI generation to produce an OpenAPI 3.1 document -->
39+
<OpenApiGenerateDocumentsOptions>
40+
--openapi-version OpenApi3_1
41+
</OpenApiGenerateDocumentsOptions>
4342
```
4443

4544
## Package installation
4645

47-
Install the `Microsoft.AspNetCore.OpenApi` package:
46+
Install the [`Microsoft.AspNetCore.OpenApi` package](https://www.nuget.org/packages/Microsoft.AspNetCore.OpenApi):
4847

49-
### [Visual Studio](#tab/visual-studio)
48+
# [Visual Studio](#tab/visual-studio)
5049

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

53-
```powershell
54-
Install-Package Microsoft.AspNetCore.OpenApi
52+
```powershell
53+
Install-Package Microsoft.AspNetCore.OpenApi
5554
```
5655

57-
### [.NET CLI](#tab/net-cli)
56+
# [.NET CLI](#tab/net-cli)
5857

59-
Run the following command:
58+
Run the following command in a command shell opened to the directory that contains the app's project file:
6059

6160
```dotnetcli
6261
dotnet add package Microsoft.AspNetCore.OpenApi
6362
```
63+
6464
---
6565

6666
## Configure OpenAPI document generation
@@ -72,31 +72,31 @@ The following code:
7272

7373
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_first&highlight=3,9)]
7474

75-
Launch the app and navigate to `https://localhost:<port>/openapi/v1.json` to view the generated OpenAPI document.
75+
Launch the app and navigate to `https://localhost:{port}/openapi/v1.json` to view the generated OpenAPI document, where the `{port}` placeholder is the port.
7676

7777
## Options to Customize OpenAPI document generation
7878

7979
The following sections demonstrate how to customize OpenAPI document generation.
8080

8181
### Generate OpenAPI document in YAML format
8282

83-
The OpenAPI document can be generated in either JSON or YAML format. By default, the OpenAPI document is generated in JSON format. To generate the OpenAPI document in YAML format, specify the endpoint in the MapOpenApi call with a ".yaml" or ".yml" suffix, as shown in the following example:
83+
The OpenAPI document can be generated in either JSON or YAML format. By default, the OpenAPI document is generated in JSON format. To generate the OpenAPI document in YAML format, specify the endpoint in the <xref:Microsoft.AspNetCore.Builder.OpenApiEndpointRouteBuilderExtensions.MapOpenApi%2A> call with a "`.yaml`" or "`.yml`" suffix, as shown in the following example, where the `{documentName}` placeholder is the document name:
8484

8585
```csharp
8686
app.MapOpenApi("/openapi/{documentName}.yaml");
8787
```
8888

89-
Generating OpenAPI documents in YAML format at build time is currently not supported, but planned in a future preview.
89+
Generating OpenAPI documents in YAML format at build time isn't supported but planned for a future preview.
9090

9191
### Customize the OpenAPI document name
9292

93-
Each OpenAPI document in an app has a unique name. The default document name that is registered is `v1`.
93+
Each OpenAPI document in an app has a unique name. The default document name that is registered is `v1`:
9494

9595
```csharp
9696
builder.Services.AddOpenApi(); // Document name is v1
9797
```
9898

99-
The document name can be modified by passing the name as a parameter to the <xref:Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi%2A> call.
99+
The document name can be modified by passing the name as a parameter to the <xref:Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi%2A> call:
100100

101101
```csharp
102102
builder.Services.AddOpenApi("internal"); // Document name is internal
@@ -113,7 +113,7 @@ GET http://localhost:5000/openapi/internal.json
113113

114114
### Customize the OpenAPI version of a generated document
115115

116-
By default, OpenAPI document generation creates a document that is compliant with [OpenAPI version 3.1](https://spec.openapis.org/oas/v3.1.1.html). The following code demonstrates how to modify the default version of the OpenAPI document:
116+
By default, OpenAPI document generation creates a document that is compliant with the OpenAPI specification. The following code demonstrates how to modify the default version of the OpenAPI document:
117117

118118
```csharp
119119
builder.Services.AddOpenApi(options =>
@@ -138,7 +138,7 @@ Because the OpenAPI document is served via a route handler endpoint, any customi
138138

139139
#### Limit OpenAPI document access to authorized users
140140

141-
The OpenAPI endpoint doesn't enable any authorization checks by default. However, authorization checks can be applied to the OpenAPI document. In the following code, access to the OpenAPI document is limited to those with the `tester` role:
141+
The OpenAPI endpoint doesn't enable authorization checks by default. However, authorization checks can be applied to the OpenAPI document. In the following code, access to the OpenAPI document is limited to users with the `tester` role:
142142

143143
[!code-csharp[](~/fundamentals/openapi/samples/9.x/WebMinOpenApi/Program.cs?name=snippet_mapopenapiwithauth)]
144144

@@ -163,47 +163,49 @@ builder.Services.AddOpenApi("v1");
163163
builder.Services.AddOpenApi("v2");
164164
```
165165

166-
Each invocation of <xref:Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi%2A> can specify its own set of options, so that you can choose to use the same or different customizations for each OpenAPI document.
166+
Each invocation of <xref:Microsoft.Extensions.DependencyInjection.OpenApiServiceCollectionExtensions.AddOpenApi%2A> can specify its own set of options, so you can choose to use the same or different customizations for each OpenAPI document.
167167

168168
The framework uses the <xref:Microsoft.AspNetCore.OpenApi.OpenApiOptions.ShouldInclude> delegate method of <xref:Microsoft.AspNetCore.OpenApi.OpenApiOptions> to determine which endpoints to include in each document.
169169

170170
For each document, the <xref:Microsoft.AspNetCore.OpenApi.OpenApiOptions.ShouldInclude> delegate method is called for each endpoint in the app, passing the <xref:Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription> object for the endpoint. The method returns a boolean value indicating whether the endpoint should be included in the document. The <xref:Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription> object:
171171

172-
* contains information about the endpoint, such as the HTTP method, route, and response types
172+
* Contains information about the endpoint, such as the HTTP method, route, and response types.
173173
* Metadata attached to the endpoint via attributes or extension methods.
174174

175-
The default implementation of this delegate uses the <xref:Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription.GroupName> field of <xref:Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription>. The delegate is set on an endpoint using either the <xref:Microsoft.AspNetCore.Builder.RoutingEndpointConventionBuilderExtensions.WithGroupName%2A> extension method or the <xref:Microsoft.AspNetCore.Routing.EndpointGroupNameAttribute> attribute. `WithGroupName` or the `EndpointGroupName` attribute determines which endpoints to include in the document. Any endpoint that has not been assigned a group name is included all OpenAPI documents.
175+
The default implementation of this delegate uses the <xref:Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription.GroupName> field of <xref:Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription>. The delegate is set on an endpoint using either the <xref:Microsoft.AspNetCore.Builder.RoutingEndpointConventionBuilderExtensions.WithGroupName%2A> extension method or the <xref:Microsoft.AspNetCore.Routing.EndpointGroupNameAttribute> attribute. `WithGroupName` or the `EndpointGroupName` attribute determines which endpoints to include in the document. Any endpoint that hasn't been assigned a group name is included all OpenAPI documents.
176176

177177
```csharp
178-
// Include endpoints without a group name or with a group name that matches the document name
179-
ShouldInclude = (description) => description.GroupName == null || description.GroupName == DocumentName;
178+
// Include endpoints without a group name or with a group name
179+
// that matches the document name
180+
ShouldInclude = (description) => description.GroupName == null ||
181+
description.GroupName == DocumentName;
180182
```
181183

182-
You can customize the <xref:Microsoft.AspNetCore.OpenApi.OpenApiOptions.ShouldInclude> delegate method to include or exclude endpoints based on any criteria you choose.
184+
You can customize the <xref:Microsoft.AspNetCore.OpenApi.OpenApiOptions.ShouldInclude> delegate method to include or exclude endpoints based on any criteria.
183185

184-
## Generate OpenAPI documents at build-time
186+
## Generate OpenAPI documents at build time
185187

186-
In typical web apps, OpenAPI documents are generated at run-time and served via an HTTP request to the app server.
188+
In typical web apps, OpenAPI documents are generated at runtime and served via an HTTP request to the app server.
187189

188-
In some scenarios, it's helpful to generate the OpenAPI document during the app's build step. These scenarios include:
190+
In some scenarios, it's helpful to generate the OpenAPI document during the app's build step. These scenarios include generating OpenAPI documentation that is:
189191

190-
* Generating OpenAPI documentation that is committed into source control.
191-
* Generating OpenAPI documentation that is used for spec-based integration testing.
192-
* Generating OpenAPI documentation that is served statically from the web server.
192+
* Committed into source control.
193+
* Used for spec-based integration testing.
194+
* Served statically from the web server.
193195

194-
To add support for generating OpenAPI documents at build time, install the `Microsoft.Extensions.ApiDescription.Server` package:
196+
To add support for generating OpenAPI documents at build time, install the [`Microsoft.Extensions.ApiDescription.Server` package](https://www.nuget.org/packages/Microsoft.Extensions.ApiDescription.Server):
195197

196-
### [Visual Studio](#tab/visual-studio)
198+
# [Visual Studio](#tab/visual-studio)
197199

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

200-
```powershell
201-
Install-Package Microsoft.Extensions.ApiDescription.Server
202+
```powershell
203+
Install-Package Microsoft.Extensions.ApiDescription.Server
202204
```
203205

204-
### [.NET CLI](#tab/net-cli)
206+
# [.NET CLI](#tab/net-cli)
205207

206-
Run the following command in the directory that contains the project file:
208+
Run the following command in a command shell opened to the directory that contains the app's project file:
207209

208210
```dotnetcli
209211
dotnet add package Microsoft.Extensions.ApiDescription.Server
@@ -216,7 +218,7 @@ Upon installation, this package:
216218
* Automatically generates the Open API document(s) associated with the app during build.
217219
* Populates the Open API documents in the app's output directory.
218220

219-
If multiple documents are registered, ***and*** document name is ***not*** `v1`, it's post-fixed with the document name. E.g., `{ProjectName}_{DocumentName}.json`.
221+
If multiple documents are registered ***and*** the document name is ***not*** `v1`, the project name is post-fixed with the document name. Example: `{ProjectName}_{DocumentName}.json`. The `{ProjectName}` placeholder is the project name, and the `{DocumentName}` placeholder is the document name.
220222

221223
# [Visual Studio Code](#tab/visual-studio-code)
222224

@@ -250,64 +252,68 @@ Disable the Terminal Logger and use legacy-style logs with the [`--tl` option](/
250252
dotnet build --tl:off
251253
```
252254

253-
### Customizing build-time document generation
255+
### Customize build-time document generation
254256

255-
#### Modifying the output directory of the generated Open API file
257+
#### Modify the output directory of the generated Open API file
256258

257-
By default, the generated OpenAPI document will be emitted to the app's output directory. To modify the location of the emitted file, set the target path in the `OpenApiDocumentsDirectory` property.
259+
By default, the generated OpenAPI document is emitted to the app's output directory. To modify the location of the emitted file, set the target path in the `OpenApiDocumentsDirectory` property:
258260

259261
```xml
260262
<PropertyGroup>
261263
<OpenApiDocumentsDirectory>.</OpenApiDocumentsDirectory>
262264
</PropertyGroup>
263265
```
264266

265-
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.
267+
The value of `OpenApiDocumentsDirectory` is resolved relative to the project file. Using the `.` value, as seen in the preceding example, emits the OpenAPI document in the same directory as the project file.
266268

267-
#### Modifying the output file name
269+
#### Modify the output file name
268270

269-
By default, the generated OpenAPI document will have the same name as the app's project file. To modify the name of the emitted file, set the `--file-name` argument in the `OpenApiGenerateDocumentsOptions` property.
271+
By default, the generated OpenAPI document has the same name as the app's project file. To modify the name of the emitted file, set the `--file-name` argument in the `OpenApiGenerateDocumentsOptions` property:
270272

271273
```xml
272274
<PropertyGroup>
273-
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions>
275+
<OpenApiGenerateDocumentsOptions>
276+
--file-name my-open-api
277+
</OpenApiGenerateDocumentsOptions>
274278
</PropertyGroup>
275279
```
276280

277-
#### Selecting the OpenAPI document to generate
281+
#### Select the OpenAPI document to generate
278282

279-
Some apps may be configured to emit multiple OpenAPI documents. Multiple OpenAPI documents may be generated for different versions of an API or to distinguish between public and internal APIs. By default, the build-time document generator emits files for all documents that are configured in an app. To only emit for a single document name, set the `--document-name` argument in the `OpenApiGenerateDocumentsOptions` property.
283+
Some apps may be configured to emit multiple OpenAPI documents. Multiple OpenAPI documents may be generated for different versions of an API or to distinguish between public and internal APIs. By default, the build-time document generator emits files for all documents that are configured in an app. To only emit for a single document name, set the `--document-name` argument in the `OpenApiGenerateDocumentsOptions` property:
280284

281285
```xml
282286
<PropertyGroup>
283-
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions>
287+
<OpenApiGenerateDocumentsOptions>
288+
--document-name v2
289+
</OpenApiGenerateDocumentsOptions>
284290
</PropertyGroup>
285291
```
286292

287-
### Customizing run-time behavior during build-time document generation
293+
### Customize runtime behavior during build-time document generation
288294

289-
Build-time OpenAPI document generation functions by launching the apps entrypoint with a mock server implementation. A mock server is required to produce accurate OpenAPI documents because all information in the OpenAPI document can't be statically analyzed. Because the apps entrypoint is invoked, any logic in the apps startup is invoked. This includes code that injects services into the [DI container](xref:fundamentals/dependency-injection) or reads from configuration. In some scenarios, it's necessary to restrict the code paths that will run when the apps entry point is being invoked from build-time document generation. These scenarios include:
295+
Build-time OpenAPI document generation functions by launching the apps entrypoint with a mock server implementation. A mock server is required to produce accurate OpenAPI documents because all information in the OpenAPI document can't be statically analyzed. Because the apps entrypoint is invoked, any logic in the apps startup is invoked. This includes code that injects services into the [DI container](xref:fundamentals/dependency-injection) or reads from configuration. In some scenarios, it's necessary to restrict the code paths when the app's entry point is invoked from build-time document generation. These scenarios include:
290296

291297
* Not reading from certain configuration strings.
292298
* Not registering database-related services.
293299

294-
In order to restrict these code paths from being invoked by the build-time generation pipeline, they can be conditioned behind a check of the entry assembly:
300+
In order to restrict invoking these code paths by the build-time generation pipeline, they can be conditioned behind a check of the entry assembly:
295301

296302
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/AspireApp1/AspireApp1.Web/Program.cs" highlight="5-8":::
297303

298-
[AddServiceDefaults](https://source.dot.net/#TestingAppHost1.ServiceDefaults/Extensions.cs,0f0d863053754768,references)<!--keep--> adds common .NET Aspire services such as service discovery, resilience, health checks, and OpenTelemetry.
304+
[`AddServiceDefaults`](https://source.dot.net/#TestingAppHost1.ServiceDefaults/Extensions.cs,0f0d863053754768,references)<!--keep--> adds common .NET Aspire services such as service discovery, resilience, health checks, and OpenTelemetry.
299305

300306
## Trimming and Native AOT
301307

302-
OpenAPI in ASP.NET Core supports trimming and native AOT. The following steps create and publish an OpenAPI app with trimming and native AOT:
308+
OpenAPI in ASP.NET Core supports trimming and native AOT. The following steps create and publish an OpenAPI app with trimming and native AOT.
303309

304-
Create a new ASP.NET Core Web API (Native AOT) project.
310+
Create a new ASP.NET Core Web API (Native AOT) project:
305311

306312
```console
307313
dotnet new webapiaot
308314
```
309315

310-
Publish the app.
316+
Publish the app:
311317

312318
```console
313319
dotnet publish

0 commit comments

Comments
 (0)