docs/configure-and-customize-cli.md
Swashbuckle.AspNetCore.CliOnce your application has been set up with Swashbuckle.AspNetCore (see Getting Started), you can use the Swashbuckle.OpenAPI CLI tool to retrieve OpenAPI JSON documents directly from your application's startup assembly, and write it to a file. This can be useful if you want to incorporate OpenAPI generation into a CI/CD process, or if you want to serve it from static file at run-time.
It's packaged as a .NET Tool that can be installed and used via the .NET SDK.
[!WARNING] The tool needs to load your Startup DLL and its dependencies at runtime. Therefore, you should use a version of the
dotnetCLI that is compatible with your application. For example, if your app targetsnet10.0, then you should use version 10.0.xxx of the .NET SDK to run the CLI tool.
To install as a global tool:
dotnet tool install -g Swashbuckle.AspNetCore.Cli
In your solution root directory, create a tool manifest file:
dotnet new tool-manifest
Install as a local tool
dotnet tool install Swashbuckle.AspNetCore.Cli
Verify that the tool was installed correctly
swagger tofile --help
Generate an OpenAPI document from your application's startup assembly
swagger tofile --output [output] [startupassembly] [swaggerdoc]
Placeholders and their meaning:
[output]: the relative path where the OpenAPI JSON document will be output to;[startupassembly]: the relative path to your application's startup assembly;[swaggerdoc]: the name of the OpenAPI document you want to generate, as configured in your application.By default, the tool will execute in the context of a "default" web host. However, in some cases you may want to bring your own host environment, for example if you've configured a custom DI container such as Autofac. For this scenario, the Swashbuckle CLI tool exposes a convention-based hook for your application.
That is, if your application contains a class that meets either of the following naming conventions, then that class will be used to provide a host for the CLI tool to run in.
public class SwaggerHostFactory, containing a public static method called CreateHost with return type IHostpublic class SwaggerWebHostFactory, containing a public static method called CreateWebHost with return type IWebHostFor example, the following class could be used to leverage the same host configuration as your application:
<!-- markdownlint-disable MD031 MD033 --> <!-- snippet: SwaggerHostFactory --><a id='snippet-SwaggerHostFactory'></a>
public class SwaggerHostFactory
{
public static IHost CreateHost()
=> MyApplication.CreateHostBuilder([]).Build();
}
<sup><a href='/test/WebSites/DocumentationSnippets/SwaggerHostFactory.cs#L3-L9' title='Snippet source file'>snippet source</a> | <a href='#snippet-SwaggerHostFactory' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet --> <!-- markdownlint-enable MD031 MD033 -->