OpenAPI specification generation
Ktor provides experimental support for generating OpenAPI specifications directly from your Kotlin code. This functionality is available via the Ktor Gradle plugin and can be combined with the OpenAPI and SwaggerUI plugins to serve interactive API documentation.
Add the Gradle plugin
To enable specification generation, apply the Ktor Gradle plugin to your project:
Configure the extension
To configure the extension, use the openApi
block inside the ktor
extension in your build.gradle.kts file. You can provide metadata such as title, description, license, and contact information:
Routing API introspection
The plugin can analyze your server routing DSL to infer basic path information, such as:
The merged path (
/api/v1/users/{id}
).Path parameters.
HTTP methods (such as
GET
andPOST
).
Because request parameters and responses are handled inside route lambdas, the plugin cannot infer detailed request/response schemas automatically. To generate a complete and useful specification, you can use annotations.
Annotate routes
To enrich the specification, Ktor uses a KDoc-like annotation API. Annotations provide metadata that cannot be inferred from code and integrate seamlessly with existing routes.
Supported KDoc fields
Tag | Format | Description |
---|---|---|
|
| Associates the endpoint with a tag for grouping |
|
| Describes a path parameter |
|
| Query parameter |
|
| Header parameter |
|
| Cookie parameter |
|
| Request body |
|
| Response with optional type |
|
| Marks endpoint deprecated |
|
| Extended description |
|
| Security requirements |
|
| External documentation links |
Generate the specification
To generate the OpenAPI specification, run the following Gradle task:
This task runs the Kotlin compiler with a custom plugin that analyzes your routing code and produces a JSON specification.
Serve the specification
To make the generated specification available at runtime, you can use the OpenAPI or SwaggerUI plugins.
The following example serves the generated specification file at an OpenAPI endpoint: