Usage Guide¶
Learn how to document your Ktor API endpoints effectively with InspeKtor.
Core Concepts¶
InspeKtor analyzes your Ktor routing DSL at compile time and automatically generates OpenAPI documentation. The key concepts are:
| Concept | Purpose |
|---|---|
| Endpoints | Route definitions and HTTP methods |
| Request Bodies | Input data schemas |
| Responses | Output data and status codes |
| Descriptions | Summaries and detailed descriptions |
| Tags | Grouping and organization |
| Parameters | Path, query, and header parameters |
The @GenerateOpenApi Annotation¶
The @GenerateOpenApi annotation is required on at least one function to enable documentation generation:
Kotlin
import io.github.tabilzad.ktor.annotations.GenerateOpenApi
@GenerateOpenApi
fun Application.module() {
routing {
// All routes defined here will be documented
}
}
You can also annotate individual route functions:
Kotlin
@GenerateOpenApi
fun Route.apiRoutes() {
route("/api") {
// Routes here will be documented
}
}
Automatic Detection¶
InspeKtor automatically detects:
- Route paths from
route(),get(),post(), etc. - Request bodies from
call.receive<T>()calls - Path parameters from
{param}syntax - Query parameters from
call.request.queryParameters - Schema types from your data classes
Documentation Annotations¶
Enhance your documentation with these annotations:
Kotlin
import io.github.tabilzad.ktor.annotations.*
import io.github.tabilzad.ktor.responds
@Tag(["Users"])
fun Route.userRoutes() {
route("/users") {
@KtorDescription(
summary = "List all users",
description = "Returns a paginated list of users"
)
get {
responds<List<User>>(HttpStatusCode.OK)
// Implementation
}
@KtorDescription(summary = "Create user")
post {
responds<User>(HttpStatusCode.Created, description = "User created")
responds<ErrorResponse>(HttpStatusCode.BadRequest)
val request = call.receive<CreateUserRequest>()
// Implementation
}
}
}
Workflow¶
- Define your routes using Ktor's routing DSL
- Add
@GenerateOpenApito your module function - Add annotations for enhanced documentation
- Build your project - spec is generated automatically
- View the spec at
build/resources/main/openapi/openapi.yaml
Quick Examples¶
Simple GET endpoint¶
Kotlin
@KtorDescription(summary = "Get server status")
get("/health") {
responds<HealthStatus>(HttpStatusCode.OK)
call.respond(HealthStatus(status = "healthy"))
}
POST with request body¶
Kotlin
@KtorDescription(summary = "Create a new product")
post("/products") {
responds<Product>(HttpStatusCode.Created)
responds<ErrorResponse>(HttpStatusCode.BadRequest)
val request = call.receive<CreateProductRequest>()
// Create product...
}
Path parameters¶
Kotlin
route("/users/{userId}") {
@KtorDescription(summary = "Get user by ID")
get {
responds<User>(HttpStatusCode.OK)
responds<ErrorResponse>(HttpStatusCode.NotFound)
val userId = call.parameters["userId"]
// Fetch user...
}
}