You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Launch the app and navigate to `https://localhost:<port>/openapi/v1.json` to view the generated OpenAPI document.
73
75
@@ -400,13 +402,13 @@ Because the OpenAPI document is served via a route handler endpoint, any customi
400
402
401
403
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:
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.
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:
@@ -452,18 +454,18 @@ Document transformers have access to a context object that includes:
452
454
453
455
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.
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:
@@ -494,13 +496,13 @@ The `Swashbuckle.AspNetCore.SwaggerUi` package provides a bundle of Swagger UI's
494
496
495
497
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 Scalar for interactive API documentation
500
502
501
503
[Scalar](https://scalar.com/) 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.
Copy file name to clipboardExpand all lines: aspnetcore/fundamentals/openapi/buildtime-openapi.md
+76-45Lines changed: 76 additions & 45 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,23 +3,27 @@ title: Generate OpenAPI documents at build time
3
3
author: captainsafia
4
4
description: Learn how to generate OpenAPI documents in your application's build step
5
5
ms.author: safia
6
-
monikerRange: '>= aspnetcore-6.0'
6
+
monikerRange: '>= aspnetcore-9.0'
7
7
ms.custom: mvc
8
8
ms.date: 8/13/2024
9
9
uid: fundamentals/openapi/buildtime-openapi
10
10
---
11
+
<!-- Per this comment by Mike, Question for @captainsafia: This doc currently says aspnetcore-6.0 and later. Should we make this just 9.0 and later, since 8.0 and earlier involve Swashbuckle or NSwag generating the doc?
<!-- backup writer.sms.author: tdykstra and rick-anderson -->
11
15
12
16
# Generate OpenAPI documents at build-time
13
17
14
-
In a typical web applications, OpenAPI documents are generated at run-time and served via an HTTP request to the application server.
18
+
In typical web apps, OpenAPI documents are generated at run-time and served via an HTTP request to the app server.
15
19
16
-
In some scenarios, it is helpful to generate the OpenAPI document during the application's build step. These scenarios including:
20
+
Generating OpenAPI documentation during the app's build step can be useful for documentation that is:
17
21
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
22
+
-Committed into source control.
23
+
-Used for spec-based integration testing.
24
+
-Served statically from the web server.
21
25
22
-
To add support for generating OpenAPI documents at build time, install the `Microsoft.Extensions.ApiDescription.Server` package:
26
+
To add support for generating OpenAPI documents at build time, install the [`Microsoft.Extensions.ApiDescription.Server`](https://www.nuget.org/packages/Microsoft.Extensions.ApiDescription.Server) NuGet package:
23
27
24
28
### [Visual Studio](#tab/visual-studio)
25
29
@@ -36,65 +40,92 @@ Run the following command in the directory that contains the project file:
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.
46
+
The `Microsoft.Extensions.ApiDescription.Server` package automatically generates the Open API document(s) associated with the app during build and places them in the app's `obj` directory:
47
+
48
+
Consider a template created API app named `MyTestApi`:
49
+
50
+
### [Visual Studio](#tab/visual-studio)
51
+
52
+
The Output tab in Visual Studio when building the app includes information similar to the following:
53
+
54
+
```text
55
+
1>Generating document named 'v1'.
56
+
1>Writing document named 'v1' to 'MyProjectPath/obj/MyTestApi.json'.
57
+
```
58
+
59
+
### [.NET CLI](#tab/net-cli)
60
+
61
+
The following commands build the app and display the generated OpenAPI document:
42
62
43
63
```cli
44
64
$ dotnet build
45
-
$ cat bin/Debub/net9.0/{ProjectName}.json
65
+
$ cat obj/MyTestApi.json
46
66
```
47
67
48
-
## Customizing build-time document generation
68
+
---
49
69
50
-
### Modifying the output directory of the generated Open API file
70
+
The generated `obj/{MyProjectName}.json` file contains the [OpenAPI version, title, endpoints, and more](https://learn.openapis.org/specification/structure.html). The first few lines of `obj/MyTestApi.json`file:
51
71
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.
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.
76
+
Build-time document generation can be customized with properties added to the project file. [dotnet](/dotnet/core/tools/) parses the `ApiDescription.Server` properties in the project file and provides the property and values as arguments to the build-time document generator. The following properties are available and explained in the following sections:
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.
80
+
### Modify the output directory of the generated Open API file
By default, the generated OpenAPI document is generated in the `obj` directory. The value of the `OpenApiDocumentsDirectory` property:
71
83
72
-
### Selecting the OpenAPI document to generate
84
+
* Sets the location of the generated file.
85
+
* Is resolved relative to the project file.
73
86
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.
87
+
The following example generates the OpenAPI document in the same directory as the project file:
## Customizing run-time behavior during build-time document generation
91
+
In the following example, the OpenAPI document is generated in the `MyOpenApiDocs` directory, which is a sibling directory to the project directory:
83
92
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:
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:
97
+
By default, the generated OpenAPI document has the same name as the app's project file. To modify the name of the generated file, set the `--file-name` argument in the `OpenApiGenerateDocumentsOptions` property:
The preceding markup configures creation of the `obj/my-open-api.json` file.
95
102
96
-
if (Assembly.GetEntryAssembly()?.GetName().Name!="GetDocument.Insider")
97
-
{
98
-
builders.Services.AddDefaults();
99
-
}
100
-
```
103
+
### Select the OpenAPI document to generate
104
+
105
+
Some apps may be configured to generate multiple OpenAPI documents, for example:
106
+
107
+
* For different versions of an API.
108
+
* To distinguish between public and internal APIs.
109
+
110
+
By default, the build-time document generator creates files for all documents that are configured in an app. To generate for a single document only, set the `--document-name` argument in the `OpenApiGenerateDocumentsOptions` property:
## Customize run-time behavior during build-time document generation
116
+
117
+
OpenAPI document generation at build-time works by starting the app’s entry point with a temporary background server. This approach is necessary to produce accurate OpenAPI documents, as not all information can be statically analyzed. When the app’s entry point is invoked, any logic in the app’s startup is executed, including code that injects services into the DI container or reads from configuration.
118
+
119
+
In some scenarios, it's important to restrict certain code paths when the app's entry point is invoked during build-time document generation. These scenarios include:
120
+
121
+
- Not reading from specific configuration strings.
122
+
- Not registering database-related services.
123
+
124
+
To prevent these code paths from being invoked by the build-time generation pipeline, they can be conditioned behind a check of the entry assembly:
The generated OpenAPI documents are not cleaned up by `dotnet clean` or **Build > Clean Solution** in Visual Studio. To remove the generated OpenAPI documents, delete the `obj` directory or the directory specified by the `OpenApiDocumentsDirectory` property.
0 commit comments