Ktor 3.0.0-beta-1 Help

Swagger UI

Ktor allows you to generate and serve Swagger UI for your project based on the existing OpenAPI specification. With Swagger UI, you can visualize and interact with the API resources.

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>

Configure Swagger UI

To serve Swagger UI, you need to call the swaggerUI method that creates a GET endpoint with Swagger UI at the path rendered from the OpenAPI specification placed at swaggerFile:

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

This method tries to look up the OpenAPI specification in the application resources. Otherwise, it tries to read the OpenAPI specification from the file system using java.io.File.

Optionally, you can customize Swagger UI inside the swaggerUI block. For example, you can use another Swagger UI version or apply a custom style.

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

You can now run the application and open the /swagger page to see the available endpoints, and test them.

Configure CORS

To make sure your API works nicely with Swagger UI, you need to set up a policy for 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 in content negotiation.

install(CORS) { anyHost() allowHeader(HttpHeaders.ContentType) }
Last modified: 02 April 2024