Swagger Export from .NETCore

Swagger Export from .NETCore

If you have an ASP.NET Web API project. Chances are you are using Swashbuckle.AspNet.Core to generate swagger documentation for the application.

Now if you need some way to export the swagger api documentation during your build for CI/CD or any other things, this is for you.

Pre-requisite

I am assuming you already have a service from which you can access the swagger JSON/UI.

Generating Swagger on Build

set up dotnet-tools

  • Run dotnet new tool-manifest at root of your project.

  • it will create a .config directory with dotnet-tools.json in it. this file will have references to the packages that you've installed.

  • install swashbuckle cli. run dotnet tool install --local Swashbuckle.AspNetCore.Cli

add post build step

  • in the project csproj file, add a new post build step.

  • add step

<Target Name="SwaggerGenerate" AfterTargets="PostBuildEvent">
    <Exec Command="dotnet tool restore" />
    <Exec Command="dotnet swagger tofile --output /path/to/swagger.json .\$(OutputPath)$(AssemblyName).dll v1" />
</Target>
  • OutputPath and AssemblyName are the project variable, and they have the path to where the build is and .dll is generated.

  • If you have multiple version of the APIs, you can have v1 or v2 in the second command.

  • Build your csproj and your openapi spec (swagger json) is created during the build.

PostScript

Feel free to reach out to me if you need any help.

linkedin.com/in/ankurcharan
instagram.com/ankurcharan
dev.to/ankurcharan
twitter.com/ankurcharan
ankurcharan.hashnode.dev