Ktor 3.0.1 Help

OpenAPI

Ktor allows you to generate and serve OpenAPI documentation for your project based on the existing OpenAPI specification.

Add dependencies

  • Serving OpenAPI documentation requires adding the ktor-server-openapi artifact in the build script:

    implementation("io.ktor:ktor-server-openapi:$ktor_version")
    implementation "io.ktor:ktor-server-openapi:$ktor_version"
    <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-openapi-jvm</artifactId> <version>${ktor_version}</version> </dependency>
  • Optionally, add the swagger-codegen-generators dependency if you want to customize a code generator:

    implementation("io.swagger.codegen.v3:swagger-codegen-generators:$swagger_codegen_version")
    implementation "io.swagger.codegen.v3:swagger-codegen-generators:$swagger_codegen_version"
    <dependency> <groupId>io.swagger.codegen.v3</groupId> <artifactId>swagger-codegen-generators</artifactId> <version>${swagger_codegen_version}</version> </dependency>

    You can replace $swagger_codegen_version with the required version of the swagger-codegen-generators artifact, for example, 1.0.36.

Configure OpenAPI

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

import io.ktor.server.plugins.openapi.* // ... routing { openAPI(path="openapi", 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.

By default, the documentation is generated using StaticHtml2Codegen. You can customize generation settings inside the openAPI block:

routing { openAPI(path="openapi", swaggerFile = "openapi/documentation.yaml") { codegen = StaticHtmlCodegen() } }

You can now run the application and open the /openapi page to see the generated documentation.

Last modified: 02 April 2024