OpenAPI
Ktor allows you to serve OpenAPI documentation based on an OpenAPI specification.
You can provide the OpenAPI specification in one of the following ways:
In both cases, the OpenAPI plugin assembles the specification on the server and renders the documentation as HTML.
Add dependencies
Serving OpenAPI documentation requires adding the
ktor-server-openapiartifact 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-generatorsdependency 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_versionwith the required version of theswagger-codegen-generatorsartifact, for example,1.0.36.
Use a static OpenAPI file
To serve OpenAPI documentation from an existing specification, use the openAPI() function with a provided path to the OpenAPI document.
The following example creates a GET endpoint at the openapi 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.
In this mode, the OpenAPI plugin assembles the specification directly from the routing tree:
With this, you can access the generated OpenAPI documentation at the /openapi path, reflecting the current state of the application.
Configure OpenAPI
By default, documentation is rendered using StaticHtml2Codegen. You can customize the renderer inside the openAPI {} block: