Good API documentation helps a developer understand the API's capabilities and how it should be used, making integration more efficient. OpenAPI is a specification used for describing REST APIs which enables you to describe your entire API. Swashbuckle is an open-source Swagger implementation used for generating Swagger documentation for .NET Core APIs using .NET reflection. It helps you automate the description process, making it easier for teams to generate, maintain, and use OpenAPI-based API documentation.
This short blog post will show how to generate the OpenApi file when you use docker. Idea is to use docker multi-stage builds and add a stage with a LABEL to output the OpenApi file. Later we can create the intermediate container to copy the OpenApi file.
Below is how the swagger publish stage looks like in dockerfile.
FROM publish AS exportswagger WORKDIR /app RUN dotnet tool install --version 6.3.1 Swashbuckle.AspNetCore.Cli --tool-path /dotnet-global-tools LABEL swagger=true RUN /dotnet-global-tools/swagger tofile --output swagger.json publish/OpenApiDockerSample.dll v1
Note that the --version should matched to the nuget version used in the .csproj file.
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.1" />
That's all we need to do. Now, when the docker build completed we can retrieve the generated file. Below is how I do it in Azure DevOps.
- script: | export swaggerimageid=$(docker images --filter "label=swagger=true" -q) docker create --name swaggercontainer $swaggerimageid docker cp swaggercontainer:/app ./swagger docker stop swaggercontainer docker rm swaggercontainer displayName: Extract Swagger doc continueOnError: false - publish: '$(System.DefaultWorkingDirectory)/swagger' displayName: 'Publish Swagger file' artifact: dropswagger
That's It! Now you can use this published swagger file and export it to Azure APIM or publish it as a static web app etc..
This will help you to generate and visualize your API documentation from the latest version of your API which is always in sync with the latest code.
Find the complete code for this in my github repo.