Generate Open API specification for ASP.NET Core projects on build

Mirza Merdovic
2 min readJun 3, 2022

In my previous post we went through how to use Open API specification and Redoc to build static documentation and deploy it to GitHub Pages. Now lets say that we want to improve on that and we want to be able to generate Open API specification upon every build automatically.

In ASP.NET Core world to decorate your API methods with Open API metadata we either use: attributes or extensions methods (minimal APIs), but these by itself will of course not produce anything, we need something that will generate the file, and that something is usually Swashbuckle.AspNetCore.

More on how to decorate your API methods and how to use Swashbuckle can be found here.

There’s one problem to get the Open API file we need to start our API, and we said that we want the file generated after the build.

Swashbuckle.AspNetCore.Cli

Luckily there is a tool that can help: Swashbuckle.AspNetCore.Cli, a tool that you can install on your machine and use it to generate Open API specification file.

Run:

dotnet tool install --global Swashbuckle.AspNetCore.Cli --version 6.3.1

It’s a very simple tool, it has just one command:

swagger tofile [options] [startupassembly] [swaggerdoc]
  • startupassembly - path to the executable of your API
  • swaggerdoc - name of the Swagger document, this is set in DI setup:
builder.Services.AddSwaggerGen(options =>
{
var info = new OpenApiInfo { Title = "My API", Version = "v1" };
options.SwaggerDoc(name: "v1", info: info);
...
});

So to generate our Open API specification in YAML format execute:

swagger tofile --output openapi.yml --yaml [path/MyApi.dll] [swagger doc name]

Automating Open API generation

We can use post MS build targets in our ASP.NET Core project to trigger a call to swagger tofile after every successful project build, to achieve that edit your project file and add the line below:

<Target Name="OpenAPI" AfterTargets="Build" Condition="$(Configuration)=='Debug'">
<Exec Command="swagger tofile --output openapi.yml --yaml $(OutputPath)$(AssemblyName).dll v1" WorkingDirectory="$(ProjectDir)" />
</Target>

This will produce a file called openapi.yml, and the file will be located in the root folder of the project.

Final thoughts

With Swashbuckle.AspNetCore.Cli and MS build targets we don’t have to do any manual work and worry if we have forgot to push new changes to the Open API specification, but this does come with a caveat of needing to install the CLI on your machine, and also to add it to your CI/CD pipeline, for some this is not a problem, but others might find it troublesome.

--

--