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
You can customize Swagger UI within the swaggerUI {} block, for example, by specifying a custom Swagger UI version:
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.