Generate OpenAPI specification at build time from the code in ASP.NET Core

 
 
  • Gérald Barré

The OpenAPI specification is a powerful tool to describe and document APIs. It is a standard that allows you to define the structure of your API, including the endpoints, the request and response models, and the security requirements. The OpenAPI specification is a JSON or YAML file that can be used to generate documentation, client libraries, and server stubs.

Most .NET developers generate the specification from the code. The Swashbuckle.AspNetCore library is a popular choice to generate the OpenAPI specification from ASP.NET Core Web API projects. You can easily add a page to access the specification. However, it's hard to validate the content of the specification to ensure the specification is usable by the consumers. One way to improve that is to make the specification part of your code, so you can review the specification during code reviews.

Microsoft provides the NuGet package Microsoft.Extensions.ApiDescription.Server that allows you to generate the OpenAPI specification from the code while building the project.

First, create a new Web API project and add the Microsoft.Extensions.ApiDescription.Server package:

Shell
dotnet new webapi --framework net8.0
dotnet add package Microsoft.Extensions.ApiDescription.Server

Then, you can add the following properties to the .csproj file to configure the generation of the OpenAPI specification:

csproj (MSBuild project file)
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>

    <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)</OpenApiDocumentsDirectory>
    <OpenApiGenerateDocuments>true</OpenApiGenerateDocuments>
    <OpenApiGenerateDocumentsOnBuild>true</OpenApiGenerateDocumentsOnBuild>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.3" />
    <PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="8.0.3">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
  </ItemGroup>

</Project>

Finally, you can build the project and check the specification is generated at the root of the project:

Shell
dotnet build

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub