-
Notifications
You must be signed in to change notification settings - Fork 25.3k
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
Fix and Edit build time OpenAPI/ra/b #33361
base: openapi-build-docs
Are you sure you want to change the base?
Changes from all commits
df65929
42711fc
1649587
446a579
f6ea15c
d1f346d
acd7cb8
a9dcecf
b074ef6
450f254
ce6735f
82d8440
29b0b19
30cb83d
aa7a993
691ddd0
967964b
7207787
830bd95
bf29769
f8c51cb
03444b0
bc64f73
8acbf92
f54bd9d
1b04232
b21f9f5
81fc99a
1a1766d
808fbb5
21e62a2
ee50266
9f95b57
b5d98ea
419d0f6
feebbda
b6469ca
38ecacb
739dcb5
52d682a
d298ace
854f69a
67c2271
0601997
df90ae3
8b6a7d5
2befcb7
025d0dc
101ac83
94bf18e
4f0bc88
a52ff1e
62e3480
078a6a6
e575f9a
3365563
49b9864
0cfbe8b
dd69fe2
7b320ba
6200d10
3dc0d25
ff894ff
5b87bda
3e4eca5
ecc1640
e607a14
c6cee5f
b798c9a
8a0df43
6276727
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,18 +8,19 @@ ms.custom: mvc | |
ms.date: 8/13/2024 | ||
uid: fundamentals/openapi/buildtime-openapi | ||
--- | ||
<!-- backup writer.sms.author: tdykstra and rick-anderson --> | ||
|
||
# Generate OpenAPI documents at build-time | ||
|
||
In a typical web applications, OpenAPI documents are generated at run-time and served via an HTTP request to the application server. | ||
In typical web apps, OpenAPI documents are generated at run-time and served via an HTTP request to the app server. | ||
|
||
In some scenarios, it is helpful to generate the OpenAPI document during the application's build step. These scenarios including: | ||
Generating OpenAPI documentation during the app's build step can be useful for documentation that is: | ||
|
||
- 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 | ||
- Committed into source control. | ||
- Used for spec-based integration testing. | ||
- Served statically from the web server. | ||
|
||
To add support for generating OpenAPI documents at build time, install the `Microsoft.Extensions.ApiDescription.Server` package: | ||
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: | ||
|
||
### [Visual Studio](#tab/visual-studio) | ||
|
||
|
@@ -36,65 +37,92 @@ 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. | ||
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: | ||
|
||
Consider a template created API app named `MyTestApi`: | ||
|
||
### [Visual Studio](#tab/visual-studio) | ||
|
||
The Output tab in Visual Studio when building the app includes information similar to the following: | ||
|
||
```text | ||
1>Generating document named 'v1'. | ||
1>Writing document named 'v1' to 'MyProjectPath/obj/MyTestApi.json'. | ||
``` | ||
|
||
### [.NET CLI](#tab/net-cli) | ||
|
||
The following commands build the app and display the generated OpenAPI document: | ||
|
||
```cli | ||
$ dotnet build | ||
$ cat bin/Debub/net9.0/{ProjectName}.json | ||
$ cat obj/MyTestApi.json | ||
``` | ||
|
||
## Customizing build-time document generation | ||
--- | ||
|
||
### Modifying the output directory of the generated Open API file | ||
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: | ||
|
||
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. | ||
:::code language="json" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.json" range="1-15" highlight="4-5"::: | ||
|
||
```xml | ||
<PropertyGroup> | ||
<OpenApiDocumentsDirectory>./</OpenApiDocumentsDirectory> | ||
Rick-Anderson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
</PropertyGroup> | ||
``` | ||
## Customize build-time document generation | ||
|
||
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. | ||
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: | ||
|
||
### Modifying the output file name | ||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet_all" highlight="2-4"::: | ||
|
||
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. | ||
### Modify the output directory of the generated Open API file | ||
|
||
```xml | ||
<PropertyGroup> | ||
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions> | ||
</PropertyGroup> | ||
``` | ||
By default, the generated OpenAPI document is generated in the `obj` directory. The value of the `OpenApiDocumentsDirectory` property: | ||
|
||
### Selecting the OpenAPI document to generate | ||
* Sets the location of the generated file. | ||
* Is resolved relative to the project file. | ||
|
||
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. | ||
The following example generates the OpenAPI document in the same directory as the project file: | ||
|
||
```xml | ||
<PropertyGroup> | ||
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions> | ||
</PropertyGroup> | ||
``` | ||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet_1" highlight="2"::: | ||
|
||
## Customizing run-time behavior during build-time document generation | ||
In the following example, the OpenAPI document is generated in the `MyOpenApiDocs` directory, which is a sibling directory to the project directory: | ||
|
||
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: | ||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet2" highlight="2"::: | ||
|
||
- Not reading from certain configuration strings | ||
- Not registering database-related services | ||
### Modify the output file name | ||
|
||
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: | ||
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: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This isn't what I've seen in my testing. I get something like There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
My build is 9.0.100-rc.1.24415.1 |
||
|
||
```csharp | ||
using System.Reflection; | ||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet_file_name" highlight="2"::: | ||
|
||
var builder = WebApplication.CreateBuilder(); | ||
The preceding markup configures creation of the `obj/my-open-api.json` file. | ||
|
||
if (Assembly.GetEntryAssembly()?.GetName().Name != "GetDocument.Insider") | ||
{ | ||
builders.Services.AddDefaults(); | ||
} | ||
``` | ||
### Select the OpenAPI document to generate | ||
|
||
Some apps may be configured to generate multiple OpenAPI documents, for example: | ||
|
||
* For different versions of an API. | ||
* To distinguish between public and internal APIs. | ||
|
||
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: | ||
|
||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet_doc_name"::: | ||
|
||
<!-- comment out this section until it's sorted | ||
## Customize run-time behavior during build-time document generation | ||
|
||
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. | ||
|
||
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: | ||
|
||
- Not reading from specific configuration strings. | ||
- Not registering database-related services. | ||
|
||
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: | ||
|
||
:::code language="csharp" source="~/fundamentals/openapi/samples/9.x/BuildTime/Skip.cs" id="snippet_1" highlight="7-12"::: | ||
--> | ||
|
||
## OpenAPI document cleanup | ||
|
||
Then 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. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<Nullable>enable</Nullable> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-rc.1.24412.15" /> | ||
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="9.0.0-rc.2.24420.12"> | ||
<PrivateAssets>all</PrivateAssets> | ||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> | ||
</PackageReference> | ||
</ItemGroup> | ||
|
||
<PropertyGroup> | ||
<DocNameV2>true</DocNameV2> | ||
</PropertyGroup> | ||
|
||
<PropertyGroup Condition=" '$(DocNameV2)' == 'true' "> | ||
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions> | ||
</PropertyGroup> | ||
|
||
</Project> |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
@MyTestApi_HostAddress = http://localhost:5276 | ||
|
||
GET {{MyTestApi_HostAddress}}/weatherforecast/ | ||
Accept: application/json | ||
|
||
### |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
builder.Services.AddOpenApi(); | ||
builder.Services.AddOpenApi("v2"); | ||
|
||
var app = builder.Build(); | ||
|
||
if (app.Environment.IsDevelopment()) | ||
{ | ||
app.MapOpenApi(); | ||
} | ||
|
||
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 | ||
( | ||
DateOnly.FromDateTime(DateTime.Now.AddDays(index)), | ||
Random.Shared.Next(-20, 55), | ||
summaries[Random.Shared.Next(summaries.Length)] | ||
)) | ||
.ToArray(); | ||
return forecast; | ||
}) | ||
.WithName("GetWeatherForecast"); | ||
|
||
app.MapGet("/v2/weatherforecast", (HttpContext httpContext) => | ||
{ | ||
var forecast = Enumerable.Range(1, 5).Select(index => | ||
new WeatherForecast | ||
( | ||
DateOnly.FromDateTime(DateTime.Now.AddDays(index)), | ||
Random.Shared.Next(-20, 55), | ||
summaries[Random.Shared.Next(summaries.Length)] | ||
)) | ||
.ToArray(); | ||
return forecast; | ||
}) | ||
.WithGroupName("v2"); | ||
Rick-Anderson marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
app.Run(); | ||
|
||
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) | ||
{ | ||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
#if NEVER | ||
// <snippet_1> | ||
using ControllerApi.Data; | ||
using Microsoft.EntityFrameworkCore; | ||
using System.Reflection; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
if (Assembly.GetEntryAssembly()?.GetName().Name != "MyTestApi") | ||
{ | ||
builder.Services.AddDbContext<ControllerApiContext>(options => | ||
options.UseSqlServer(builder.Configuration.GetConnectionString("ControllerApiContext") | ||
?? throw new InvalidOperationException("Connection string 'ControllerApiContext' not found."))); | ||
} | ||
|
||
Comment on lines
+7
to
+15
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @martincostello can you provide the code to demonstrate 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: ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @Rick-Anderson I can take care of providing the code sample for this. I'll have to take a look at it next week. |
||
builder.Services.AddControllers(); | ||
builder.Services.AddOpenApi(); | ||
|
||
var app = builder.Build(); | ||
|
||
if (app.Environment.IsDevelopment()) | ||
{ | ||
app.MapOpenApi(); | ||
} | ||
|
||
app.UseHttpsRedirection(); | ||
|
||
app.UseAuthorization(); | ||
|
||
app.MapControllers(); | ||
|
||
app.Run(); | ||
// </snippet_1> | ||
#endif |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Information", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
}, | ||
"AllowedHosts": "*" | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is obj right? I would have thought it would be in the output directory (or should be) so be within bin.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@captainsafia
drafted this as the output directory and maybe that's where it will end up. In my testing, it's in theobj
directory.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
run /TestScripts/combined.ps1
what version of RC1 do you have?
I have 9.0.100-rc.1.24415.1