Domenic
Domenic

Reputation: 738

Swagger WebApi create json on build

Is there any way to create the swagger json during the build task of my web api? I want to use the json to feed it into a code generator and generate a typescript definition file.

Any help is more than welcome!

Upvotes: 17

Views: 12260

Answers (2)

Enrico
Enrico

Reputation: 3443

I'm using Swashbuckle.AspNetCore.Cli (note: I'm using .NET Core 3.1) https://github.com/domaindrivendev/Swashbuckle.AspNetCore

Add the following packages:

<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc5" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="5.3.1" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.3.1" />

Next, create a tool manifest:

dotnet new tool-manifest

Install the Swashbuckle CLI tool and add it to the local manifest file:

dotnet tool install --version 5.3.1 Swashbuckle.AspNetCore.Cli

Now you can use a dotnet command to generate a swagger.json file. For example:

dotnet swagger tofile --output api.json bin/debug/netcoreapp3.1/xxx.yourApi.dll v1

If you want the file to be generated on each build, use a PostBuild target in your csproj file.

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="dotnet tool restore" />
    <Exec Command="dotnet swagger tofile --output swagger.json $(OutputPath)\$(AssemblyName).dll v1 " />
</Target>

Upvotes: 19

Rico Suter
Rico Suter

Reputation: 11858

You can use the NSwag command line tools like this:

nswag.exe webapi2swagger /assembly:"path/to/assembly.dll" /output:"path/to/swagger.json"

This generates a Swagger specification with for all controllers in the given DLL.

For more information read this page.

Upvotes: 7

Related Questions