Swagger UI
Ktor allows you to generate and serve Swagger UI for your project based on an OpenAPI specification. With Swagger UI, you can visualize and interact with your API endpoints directly from the browser.
You can provide the OpenAPI specification in one of the following ways:
Add dependencies
Serving Swagger UI requires adding the ktor-server-swagger artifact in the build script:
Use a static OpenAPI file
To serve Swagger UI from an existing OpenAPI specification file, use the swaggerUI() function and specify the file location.
The following example creates a GET endpoint at the swagger path and renders the Swagger UI from the provided OpenAPI specification file:
The plugin first looks for the specification in the application resources. If not found, it attempts to load it from the file system using java.io.File.
Generate runtime OpenAPI metadata
Instead of relying on a static file, you can generate the OpenAPI specification at runtime using metadata produced by the OpenAPI compiler plugin and route annotations:
With this, you can access the generated OpenAPI documentation at the /swaggerUI path, reflecting the current state of the application.
Configure Swagger UI
The swaggerUI {} configuration block lets you configure the OpenAPI document and customize Swagger UI.
Configure document metadata
You can define top-level OpenAPI metadata directly in the configuration block.
For example, use info to specify general API information and tag() to define tags and their descriptions:
You can also configure other top-level OpenAPI properties, such as servers, security requirements, reusable components, external documentation, and specification extensions.
Configure the Swagger UI version
By default, Ktor uses a predefined Swagger UI version. To use a different version, set the version property:
Configure CORS
To ensure Swagger UI can access your API endpoints correctly, you need to first configure Cross-Origin Resource Sharing (CORS).
The example below applies the following CORS configuration:
anyHostenables cross-origin requests from any host.allowHeaderallows theContent-Typeclient header used for content negotiation.