Ktor 3.4.0 Help

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:

implementation("io.ktor:ktor-server-swagger:$ktor_version")
implementation "io.ktor:ktor-server-swagger:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-swagger-jvm</artifactId> <version>${ktor_version}</version> </dependency>

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:

import io.ktor.server.plugins.swagger.* // ... routing { swaggerUI(path = "swagger", swaggerFile = "openapi/documentation.yaml") }

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:

swaggerUI("/swaggerUI") { info = OpenApiInfo("My API", "1.0") source = OpenApiDocSource.Routing(ContentType.Application.Json) { routingRoot.descendants() } }

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:

routing { swaggerUI(path = "swagger", swaggerFile = "openapi/documentation.yaml") { version = "4.15.5" } }

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:

  • anyHost enables cross-origin requests from any host.

  • allowHeader allows the Content-Type client header used for content negotiation.

install(CORS) { anyHost() allowHeader(HttpHeaders.ContentType) }
23 January 2026