-
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
FROZEN: Add build-time OpenAPI generation doc #33359
Draft
captainsafia
wants to merge
2
commits into
main
Choose a base branch
from
openapi-build-docs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
--- | ||
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-9.0' | ||
ms.custom: mvc | ||
ms.date: 8/13/2024 | ||
uid: fundamentals/openapi/buildtime-openapi | ||
--- | ||
<!-- 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? | ||
I made it 9.0 | ||
https://github.com/dotnet/AspNetCore.Docs/pull/33361#discussion_r1778546753 --> | ||
<!-- backup writer.sms.author: tdykstra and rick-anderson --> | ||
|
||
# Generate OpenAPI documents at build-time | ||
|
||
In typical web apps, OpenAPI documents are generated at run-time and served via an HTTP request to the app server. | ||
|
||
Generating OpenAPI documentation during the app's build step can be useful for documentation that is: | ||
|
||
- 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`](https://www.nuget.org/packages/Microsoft.Extensions.ApiDescription.Server) NuGet 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 | ||
``` | ||
|
||
--- | ||
|
||
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 obj/MyTestApi.json | ||
``` | ||
|
||
--- | ||
|
||
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: | ||
|
||
:::code language="json" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.json" range="1-15" highlight="4-5"::: | ||
|
||
## Customize build-time document generation | ||
|
||
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: | ||
|
||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet_all" highlight="2-4"::: | ||
|
||
### 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: | ||
|
||
* Sets the location of the generated file. | ||
* Is resolved relative to the project file. | ||
|
||
The following example generates the OpenAPI document in the same directory as the project file: | ||
|
||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet_1" highlight="2"::: | ||
|
||
In the following example, the OpenAPI document is generated in the `MyOpenApiDocs` directory, which is a sibling directory to the project directory: | ||
|
||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet2" highlight="2"::: | ||
|
||
### Modify the output file name | ||
|
||
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: | ||
|
||
:::code language="xml" source="~/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php" id="snippet_file_name" highlight="2"::: | ||
|
||
The preceding markup configures creation of the `obj/my-open-api.json` file. | ||
|
||
### 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 | ||
|
||
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. |
25 changes: 25 additions & 0 deletions
25
aspnetcore/fundamentals/openapi/samples/9.x/BuildTime/MyTestApi.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
6 changes: 6 additions & 0 deletions
6
aspnetcore/fundamentals/openapi/samples/9.x/BuildTime/MyTestApi.http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
### |
53 changes: 53 additions & 0 deletions
53
aspnetcore/fundamentals/openapi/samples/9.x/BuildTime/Program.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | ||
|
||
app.Run(); | ||
|
||
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) | ||
{ | ||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); | ||
} |
34 changes: 34 additions & 0 deletions
34
aspnetcore/fundamentals/openapi/samples/9.x/BuildTime/Skip.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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."))); | ||
} | ||
|
||
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 |
File renamed without changes.
File renamed without changes.
39 changes: 39 additions & 0 deletions
39
aspnetcore/fundamentals/openapi/samples/9.x/BuildTime/csproj/MyTestApi.csproj.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
<!-- | ||
This file is needed to contain snippets and provides a convenient | ||
location to copy/paste the <PropertyGroup> into the .csproj file. | ||
The dash dash sequence is an illegal string in an XML comment and | ||
results in the error: An XML comment cannot contain --. | ||
That's why this is stored as an HTML file. | ||
--> | ||
|
||
<!-- <snippet_file_name> --> | ||
<PropertyGroup> | ||
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions> | ||
</PropertyGroup> | ||
<!-- </snippet_file_name> --> | ||
|
||
<!--<snippet_1>--> | ||
<PropertyGroup> | ||
<OpenApiDocumentsDirectory>.</OpenApiDocumentsDirectory> | ||
</PropertyGroup> | ||
<!--</snippet_1>--> | ||
<!--<snippet2>--> | ||
<PropertyGroup> | ||
<OpenApiDocumentsDirectory>../MyOpenApiDocs</OpenApiDocumentsDirectory> | ||
</PropertyGroup> | ||
<!--</snippet2>--> | ||
|
||
<!--<snippet_doc_name>--> | ||
<PropertyGroup> | ||
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions> | ||
</PropertyGroup> | ||
<!--</snippet_doc_name>--> | ||
|
||
<!-- <snippet_all> --> | ||
<PropertyGroup> | ||
<OpenApiDocumentsDirectory>.</OpenApiDocumentsDirectory> | ||
<OpenApiGenerateDocumentsOptions>--file-name my-open-api</OpenApiGenerateDocumentsOptions> | ||
<OpenApiGenerateDocumentsOptions>--document-name v2</OpenApiGenerateDocumentsOptions> | ||
</PropertyGroup> | ||
<!-- </snippet_all> --> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
@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.
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.
Can I merge #33361 into this branch? You've reviewed #33361 and @mikekistler has approved my changes. My PR fixes the toc.yml merge conflict. I think I can easily fix the other merge conflicts.