
Interface-driven, data-bound controllers for Ktor servers, enabling typed request/response objects, automatic content negotiation, role-based authorization, declarative validation, and zero-reflection routing to reduce boilerplate.
A Kotlin multiplatform library that brings interface-driven, data-bound controller patterns to Ktor 2 servers.
It gives you a clean separation between your API specification (what an endpoint accepts and produces) and your business logic (what it actually does) — similar to how Spring MVC's @RestController and @RequestMapping annotations work, but using idiomatic Kotlin interfaces and type safety instead of annotations.
Ktor's routing DSL is flexible but low-level: request parsing, type conversion, header extraction, content-type negotiation, role checks, and response building are all left to you. As projects grow, routing handlers tend to accumulate boilerplate and become hard to test in isolation.
ktor2-server-bind solves this by providing:
Accept and Content-Type headers are validated automatically against the endpoint's produces/consumes declarations.RouteConfig using libraries like Konform; integrated with Ktor's RequestValidation plugin.400 Bad Request.Add the dependency to your Gradle build:
// build.gradle.kts
dependencies {
implementation("io.withlambda:ktor2-server-bind:1.0.0")
}Or with a version catalog (libs.versions.toml):
[versions]
ktor2-server-bind = "1.0.0"
[libraries]
ktor2-server-bind = { module = "io.withlambda:ktor2-server-bind", version.ref = "ktor2-server-bind" }// build.gradle.kts
dependencies {
implementation(libs.ktor2.server.bind)
}Compatibility: Requires Ktor
2.0.0+and JVM 8+.
| Concept | Role |
|---|---|
Controller |
Groups a set of endpoints together and installs them into Ktor routing |
RouteConfig |
Defines what an endpoint looks like — path, method, content types, parameter extraction |
RouteProcessor |
Defines how an endpoint works — receives typed request data, returns typed response data |
RequestData |
Typed container for path params, query params, headers, and optional body |
ResponseData |
Typed container for HTTP status code, optional body, optional message, optional response headers |
ResponseHeaders |
Typed container for response headers sent back to the client |
The following shows a full example of a POST /greetings/{name} endpoint.
@Serializable
data class GreetingRequest(val message: String)
@Serializable
data class GreetingResponse(val greeting: String)A RouteConfig object declares everything about an endpoint: its path, method, content types, and how to extract typed parameters from the incoming ApplicationCall.
object CreateGreeting : PostRouteConfig {
// -- Typed path parameters
class PathParametersImpl(val name: String) : PathParameters
// -- Typed optional query parameters
class OptionalQueryParametersImpl(val locale: String?) : OptionalQueryParameters
// -- Typed required query parameters
class RequiredQueryParametersImpl(val version: Int) : RequiredQueryParameters
// -- Typed request headers
class RequestHeadersImpl(val traceId: String?) : RequestHeaders
// -- Combined typed request data (path + query + headers + body)
class RequestDataImpl(
override val pathParameter: PathParametersImpl,
override val optionalQueryParameter: OptionalQueryParametersImpl,
override val requiredQueryParameter: RequiredQueryParametersImpl,
override val headers: RequestHeadersImpl,
override val requestBody: GreetingRequest
) : RequestWithBodyData<GreetingRequest>
// -- Typed response data
class ResponseDataImpl(
override val httpStatusCode: HttpStatusCode,
override val responseBody: GreetingResponse?,
override val responseMessage: String?,
override val responseHeaders: Nothing? = null
) : ResponseDataWithBody<GreetingResponse>
// -- Endpoint declaration: POST /greetings/{name}, JSON in and out
override val requestMapping = PostRequestMapping(
name = "createGreeting",
path = "/greetings/{name}",
produces = ContentType.Application.Json,
consumes = ContentType.Application.Json
)
override val conversionService = DefaultConversionService
// -- Role-based authorization (empty set = no roles required)
override val roleBasedAuthorizationConfiguration = RoleBasedAuthorizationConfigurationImpl(
enabled = false,
requiredRolesAllOf = emptySet()
)
// -- Extract typed path parameters from the call
override suspend fun ApplicationCall.getPathParameters(): PathParametersImpl {
val name: String by RequiredParametersHandler(parameters, conversionService)
return PathParametersImpl(name = name)
}
// -- Extract optional query parameters
override suspend fun ApplicationCall.getOptionalQueryParameters(): OptionalQueryParametersImpl {
val locale: String? by OptionalParametersHandler(request.queryParameters, conversionService)
return OptionalQueryParametersImpl(locale = locale)
}
// -- Extract required query parameters
override suspend fun ApplicationCall.getRequiredQueryParameters(): RequiredQueryParametersImpl {
val version: Int by RequiredParametersHandler(request.queryParameters, conversionService)
return RequiredQueryParametersImpl(version = version)
}
// -- Extract request headers
override suspend fun ApplicationCall.getRequestHeaders(): RequestHeadersImpl {
val traceId: String? by OptionalHeadersHandler(request.headers, conversionService)
return RequestHeadersImpl(traceId = traceId)
}
// -- The RouteProcessor: wires request data extraction to a business logic function
class RouteProcessorImpl(
override val requestMapping: PostRequestMapping = CreateGreeting.requestMapping,
override val roleBasedAuthorizationConfiguration: RoleBasedAuthorizationConfigurationImpl =
CreateGreeting.roleBasedAuthorizationConfiguration,
override val processRequest: suspend PipelineContext<Unit, ApplicationCall>.(
RequestDataImpl
) -> ResponseDataImpl
) : PostRouteProcessor<GreetingRequest, RequestDataImpl, GreetingResponse, ResponseDataImpl> {
override suspend fun ApplicationCall.prepareRequestData() = RequestDataImpl(
pathParameter = getPathParameters(),
optionalQueryParameter = getOptionalQueryParameters(),
requiredQueryParameter = getRequiredQueryParameters(),
headers = getRequestHeaders(),
requestBody = receive()
)
override suspend fun ApplicationCall.respondWithBody(
httpStatusCode: HttpStatusCode,
responseBody: GreetingResponse
) = respond(httpStatusCode, responseBody)
}
}interface GreetingController : Controller {
val createGreeting: CreateGreeting.RouteProcessorImpl
override val endpoints: List<RouteProcessorBase<*, *, *>>
get() = listOf(createGreeting)
}object GreetingControllerImpl : GreetingController {
override val authenticationConfiguration: AuthenticationConfiguration =
AUTHENTICATION_CONFIGURATION_DEFAULT
override val createGreeting = CreateGreeting.RouteProcessorImpl(
processRequest = { requestData ->
val greeting = "Hello, ${requestData.pathParameter.name}! You said: ${requestData.requestBody.message}"
CreateGreeting.ResponseDataImpl(
httpStatusCode = HttpStatusCode.Created,
responseBody = GreetingResponse(greeting),
responseMessage = null
)
}
)
}fun Application.configureRouting() {
routing {
install(GreetingControllerImpl)
}
}That's it. The library automatically:
POST /greetings/{name} to your handlerAccept: application/json and Content-Type: application/json
All standard HTTP methods have a matching pair of RouteConfig and RouteProcessor interfaces:
| HTTP Method | RouteConfig interface | RouteProcessor interface |
|---|---|---|
| GET | GetRouteConfig |
GetRouteProcessor |
| POST | PostRouteConfig |
PostRouteProcessor |
| PUT | PutRouteConfig |
PutRouteProcessor |
| PATCH | PatchRouteConfig |
PatchRouteProcessor |
| DELETE | DeleteRouteConfig |
DeleteRouteProcessor |
| HEAD | HeadRouteConfig |
HeadRouteProcessor |
| OPTIONS | OptionsRouteConfig |
OptionsRouteProcessor |
ktor2-server-bind provides delegate-based helpers to extract and type-convert parameters from ApplicationCall:
// Required parameter — throws MissingRequestParameterException if absent
val id: Int by RequiredParametersHandler(parameters, conversionService)
// Optional parameter — returns null if absent
val page: Int? by OptionalParametersHandler(request.queryParameters, conversionService)
// Required header — throws MissingHeaderException if absent
val authorization: String by RequiredHeadersHandler(request.headers, conversionService)
// Optional header — returns null if absent
val traceId: String? by OptionalHeadersHandler(request.headers, conversionService)The variable name is used as the parameter key automatically via Kotlin property delegates.
Set authenticationConfiguration on your controller to wrap all its endpoints in Ktor's authenticate {} block:
override val authenticationConfiguration = AuthenticationConfigurationImpl(
enable = true,
providers = arrayOf("jwt"), // matches your Ktor auth provider name
optional = false
)Use AUTHENTICATION_CONFIGURATION_DEFAULT to enable authentication for a controller using the default unnamed provider (equivalent to Ktor's authenticate(null)).
Each RouteProcessor carries its own roleBasedAuthorizationConfiguration. Use RoleBasedAuthorizationConfigurationImpl to enforce that the authenticated principal holds all required roles:
override val roleBasedAuthorizationConfiguration = RoleBasedAuthorizationConfigurationImpl(
enabled = true,
requiredRolesAllOf = setOf("ADMIN", "WRITE_GREETINGS")
)Your principal must implement PrincipalRoles so the library can inspect its roles:
data class UserPrincipal(
val userId: String,
override val roles: Set<String>
) : Principal, PrincipalRolesktor2-server-bind supports declarative validation of request bodies. You can define validation rules in your RouteConfig using a Multiplatform-friendly validation library (e.g., Konform).
object CreateGreeting : PostRouteConfig<GreetingRequest> {
// ...
override val validation = Validation {
GreetingRequest::message {
minLength(5)
}
}
}The library automatically bridges your RouteConfig.validation to Ktor's RequestValidation plugin when you call install() on your controller or route processor.
Register the predefined exception handler in Ktor's StatusPages plugin to automatically map validation failures to 400 Bad Request responses with structured error messages:
install(StatusPages) {
predefinedBadRequestExceptionsHandler()
}Install the predefined bad-request exception handler inside Ktor's StatusPages plugin to automatically respond 400 Bad Request when required parameters or headers are missing or cannot be converted:
install(StatusPages) {
predefinedBadRequestExceptionsHandler()
}This handles:
MissingRequestParameterException — a required query or path parameter is absentParameterConversionException — a parameter value cannot be converted to the target typeMissingHeaderException — a required header is absentBindValidationException — a request body fails validation (returns structured errors)You can supply a custom handler builder to override the default behavior:
install(StatusPages) {
predefinedBadRequestExceptionsHandler(
predefinedBadExceptionsHandlerBuilder = ExceptionHandling.defaultPredefinedBadExceptionsHandlerBuilder
)
}ktor2-server-bind ships a companion KSP annotation processor, ktor2-server-bind-processor, that inspects your controllers at compile time and writes an openapi.json resource file to the build output — no reflection, no runtime overhead.
Apply the KSP plugin and add the processor as a ksp dependency alongside the main library:
// build.gradle.kts
plugins {
id("com.google.devtools.ksp") version "<ksp-version>"
}
dependencies {
implementation("io.withlambda:ktor2-server-bind:<version>")
ksp("io.withlambda:ktor2-server-bind-processor:<version>")
}Mark each controller class with @ApiController (use tag to group endpoints in the spec) and each RouteProcessor property with @ApiEndpoint:
@ApiController(tag = "Greetings")
interface GreetingController : Controller {
@ApiEndpoint(path = "/greetings/{name}", summary = "Create a greeting")
val createGreeting: CreateGreeting.RouteProcessorImpl
}After the next build, openapi.json is written to the resources output directory and is available on the classpath. Serve it with the built-in OpenApiRoute:
routing {
openApiRoute() // GET /openapi.json
}ktor2-server-bind is an ideal foundation for building a Ktor server generator for the OpenAPI Generator project, enabling a fully spec-first (design-first) workflow for Ktor APIs.
In a spec-first approach you write your OpenAPI specification (openapi.yaml) before writing any code. A code generator then reads that specification and produces:
RouteConfig objects — one per operation, fully typed with the path, HTTP method, content types, path/query parameters, request body, and response models derived directly from the spec.@Serializable annotations, matching the spec's components/schemas.Because ktor2-server-bind already separates the shape of an endpoint (RouteConfig) from its behavior (RouteProcessor), the boundary between generated and handwritten code is clean: the generator owns the interfaces and configs, you own the implementations.
| OpenAPI concept |
ktor2-server-bind equivalent |
|---|---|
Operation (operationId) |
RouteConfig object + RouteProcessor implementation |
| Tag |
Controller interface grouping related RouteProcessors |
parameters (path, query, header) |
Typed PathParameters, RequiredQueryParameters, RequestHeaders inner classes |
requestBody |
Typed body extracted via receive<T>() in prepareRequestData()
|
responses |
Typed ResponseData / ResponseDataWithBody return values |
security |
AuthenticationConfiguration + RoleBasedAuthorizationConfiguration
|
Given an OpenAPI spec with:
paths:
/pets:
post:
operationId: createPet
tags: [Pets]
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/NewPet'
responses:
'201':
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'A Ktor generator built on ktor2-server-bind would emit:
// Generated — do not edit
object CreatePet : PostRouteConfig {
class RequestDataImpl(
override val pathParameter: Nothing? = null,
override val optionalQueryParameter: Nothing? = null,
override val requiredQueryParameter: Nothing? = null,
override val headers: Nothing? = null,
override val requestBody: NewPet
) : RequestWithBodyData<NewPet>
class ResponseDataImpl(
override val httpStatusCode: HttpStatusCode,
override val responseBody: Pet?,
override val responseMessage: String?,
override val responseHeaders: Nothing? = null
) : ResponseDataWithBody<Pet>
override val requestMapping = PostRequestMapping(
name = "createPet",
path = "/pets",
produces = ContentType.Application.Json,
consumes = ContentType.Application.Json
)
// ... conversionService, roleBasedAuthorizationConfiguration, parameter extractors
}
// Generated — do not edit
interface PetsController : Controller {
val createPet: CreatePet.RouteProcessorImpl
override val endpoints get() = listOf(createPet)
}You then implement only the business logic:
// Handwritten — your code
object PetsControllerImpl : PetsController {
override val authenticationConfiguration = AUTHENTICATION_CONFIGURATION_DEFAULT
override val createPet = CreatePet.RouteProcessorImpl { requestData ->
val saved = petService.save(requestData.requestBody)
CreatePet.ResponseDataImpl(HttpStatusCode.Created, saved, null)
}
}If you are interested in contributing a kotlin-ktor-server generator template to the OpenAPI Generator project, ktor2-server-bind provides all the runtime primitives the generated code needs — no additional runtime dependencies required beyond Ktor itself. See the OpenAPI Generator contribution guide for how to add a new server generator.
The build is pre-configured to publish to Maven Central via OSSRH (Sonatype OSS Repository Hosting).
For full instructions — what OSSRH is, how to get and configure credentials, GPG signing setup, local publishing steps, and a pre-release checklist — see PUBLISHING.md.
A GitHub Actions workflow is also provided at .github/workflows/publish.yml. Trigger it manually from the Actions tab, choose snapshot or release, and the pipeline handles the rest (signing included for releases).
For instructions on how to contribute to the project, including environment setup, code style (ktlint/detekt), and running tests, please see CONTRIBUTE.md.
Copyright 2024 withLambda
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
A Kotlin multiplatform library that brings interface-driven, data-bound controller patterns to Ktor 2 servers.
It gives you a clean separation between your API specification (what an endpoint accepts and produces) and your business logic (what it actually does) — similar to how Spring MVC's @RestController and @RequestMapping annotations work, but using idiomatic Kotlin interfaces and type safety instead of annotations.
Ktor's routing DSL is flexible but low-level: request parsing, type conversion, header extraction, content-type negotiation, role checks, and response building are all left to you. As projects grow, routing handlers tend to accumulate boilerplate and become hard to test in isolation.
ktor2-server-bind solves this by providing:
Accept and Content-Type headers are validated automatically against the endpoint's produces/consumes declarations.RouteConfig using libraries like Konform; integrated with Ktor's RequestValidation plugin.400 Bad Request.Add the dependency to your Gradle build:
// build.gradle.kts
dependencies {
implementation("io.withlambda:ktor2-server-bind:1.0.0")
}Or with a version catalog (libs.versions.toml):
[versions]
ktor2-server-bind = "1.0.0"
[libraries]
ktor2-server-bind = { module = "io.withlambda:ktor2-server-bind", version.ref = "ktor2-server-bind" }// build.gradle.kts
dependencies {
implementation(libs.ktor2.server.bind)
}Compatibility: Requires Ktor
2.0.0+and JVM 8+.
| Concept | Role |
|---|---|
Controller |
Groups a set of endpoints together and installs them into Ktor routing |
RouteConfig |
Defines what an endpoint looks like — path, method, content types, parameter extraction |
RouteProcessor |
Defines how an endpoint works — receives typed request data, returns typed response data |
RequestData |
Typed container for path params, query params, headers, and optional body |
ResponseData |
Typed container for HTTP status code, optional body, optional message, optional response headers |
ResponseHeaders |
Typed container for response headers sent back to the client |
The following shows a full example of a POST /greetings/{name} endpoint.
@Serializable
data class GreetingRequest(val message: String)
@Serializable
data class GreetingResponse(val greeting: String)A RouteConfig object declares everything about an endpoint: its path, method, content types, and how to extract typed parameters from the incoming ApplicationCall.
object CreateGreeting : PostRouteConfig {
// -- Typed path parameters
class PathParametersImpl(val name: String) : PathParameters
// -- Typed optional query parameters
class OptionalQueryParametersImpl(val locale: String?) : OptionalQueryParameters
// -- Typed required query parameters
class RequiredQueryParametersImpl(val version: Int) : RequiredQueryParameters
// -- Typed request headers
class RequestHeadersImpl(val traceId: String?) : RequestHeaders
// -- Combined typed request data (path + query + headers + body)
class RequestDataImpl(
override val pathParameter: PathParametersImpl,
override val optionalQueryParameter: OptionalQueryParametersImpl,
override val requiredQueryParameter: RequiredQueryParametersImpl,
override val headers: RequestHeadersImpl,
override val requestBody: GreetingRequest
) : RequestWithBodyData<GreetingRequest>
// -- Typed response data
class ResponseDataImpl(
override val httpStatusCode: HttpStatusCode,
override val responseBody: GreetingResponse?,
override val responseMessage: String?,
override val responseHeaders: Nothing? = null
) : ResponseDataWithBody<GreetingResponse>
// -- Endpoint declaration: POST /greetings/{name}, JSON in and out
override val requestMapping = PostRequestMapping(
name = "createGreeting",
path = "/greetings/{name}",
produces = ContentType.Application.Json,
consumes = ContentType.Application.Json
)
override val conversionService = DefaultConversionService
// -- Role-based authorization (empty set = no roles required)
override val roleBasedAuthorizationConfiguration = RoleBasedAuthorizationConfigurationImpl(
enabled = false,
requiredRolesAllOf = emptySet()
)
// -- Extract typed path parameters from the call
override suspend fun ApplicationCall.getPathParameters(): PathParametersImpl {
val name: String by RequiredParametersHandler(parameters, conversionService)
return PathParametersImpl(name = name)
}
// -- Extract optional query parameters
override suspend fun ApplicationCall.getOptionalQueryParameters(): OptionalQueryParametersImpl {
val locale: String? by OptionalParametersHandler(request.queryParameters, conversionService)
return OptionalQueryParametersImpl(locale = locale)
}
// -- Extract required query parameters
override suspend fun ApplicationCall.getRequiredQueryParameters(): RequiredQueryParametersImpl {
val version: Int by RequiredParametersHandler(request.queryParameters, conversionService)
return RequiredQueryParametersImpl(version = version)
}
// -- Extract request headers
override suspend fun ApplicationCall.getRequestHeaders(): RequestHeadersImpl {
val traceId: String? by OptionalHeadersHandler(request.headers, conversionService)
return RequestHeadersImpl(traceId = traceId)
}
// -- The RouteProcessor: wires request data extraction to a business logic function
class RouteProcessorImpl(
override val requestMapping: PostRequestMapping = CreateGreeting.requestMapping,
override val roleBasedAuthorizationConfiguration: RoleBasedAuthorizationConfigurationImpl =
CreateGreeting.roleBasedAuthorizationConfiguration,
override val processRequest: suspend PipelineContext<Unit, ApplicationCall>.(
RequestDataImpl
) -> ResponseDataImpl
) : PostRouteProcessor<GreetingRequest, RequestDataImpl, GreetingResponse, ResponseDataImpl> {
override suspend fun ApplicationCall.prepareRequestData() = RequestDataImpl(
pathParameter = getPathParameters(),
optionalQueryParameter = getOptionalQueryParameters(),
requiredQueryParameter = getRequiredQueryParameters(),
headers = getRequestHeaders(),
requestBody = receive()
)
override suspend fun ApplicationCall.respondWithBody(
httpStatusCode: HttpStatusCode,
responseBody: GreetingResponse
) = respond(httpStatusCode, responseBody)
}
}interface GreetingController : Controller {
val createGreeting: CreateGreeting.RouteProcessorImpl
override val endpoints: List<RouteProcessorBase<*, *, *>>
get() = listOf(createGreeting)
}object GreetingControllerImpl : GreetingController {
override val authenticationConfiguration: AuthenticationConfiguration =
AUTHENTICATION_CONFIGURATION_DEFAULT
override val createGreeting = CreateGreeting.RouteProcessorImpl(
processRequest = { requestData ->
val greeting = "Hello, ${requestData.pathParameter.name}! You said: ${requestData.requestBody.message}"
CreateGreeting.ResponseDataImpl(
httpStatusCode = HttpStatusCode.Created,
responseBody = GreetingResponse(greeting),
responseMessage = null
)
}
)
}fun Application.configureRouting() {
routing {
install(GreetingControllerImpl)
}
}That's it. The library automatically:
POST /greetings/{name} to your handlerAccept: application/json and Content-Type: application/json
All standard HTTP methods have a matching pair of RouteConfig and RouteProcessor interfaces:
| HTTP Method | RouteConfig interface | RouteProcessor interface |
|---|---|---|
| GET | GetRouteConfig |
GetRouteProcessor |
| POST | PostRouteConfig |
PostRouteProcessor |
| PUT | PutRouteConfig |
PutRouteProcessor |
| PATCH | PatchRouteConfig |
PatchRouteProcessor |
| DELETE | DeleteRouteConfig |
DeleteRouteProcessor |
| HEAD | HeadRouteConfig |
HeadRouteProcessor |
| OPTIONS | OptionsRouteConfig |
OptionsRouteProcessor |
ktor2-server-bind provides delegate-based helpers to extract and type-convert parameters from ApplicationCall:
// Required parameter — throws MissingRequestParameterException if absent
val id: Int by RequiredParametersHandler(parameters, conversionService)
// Optional parameter — returns null if absent
val page: Int? by OptionalParametersHandler(request.queryParameters, conversionService)
// Required header — throws MissingHeaderException if absent
val authorization: String by RequiredHeadersHandler(request.headers, conversionService)
// Optional header — returns null if absent
val traceId: String? by OptionalHeadersHandler(request.headers, conversionService)The variable name is used as the parameter key automatically via Kotlin property delegates.
Set authenticationConfiguration on your controller to wrap all its endpoints in Ktor's authenticate {} block:
override val authenticationConfiguration = AuthenticationConfigurationImpl(
enable = true,
providers = arrayOf("jwt"), // matches your Ktor auth provider name
optional = false
)Use AUTHENTICATION_CONFIGURATION_DEFAULT to enable authentication for a controller using the default unnamed provider (equivalent to Ktor's authenticate(null)).
Each RouteProcessor carries its own roleBasedAuthorizationConfiguration. Use RoleBasedAuthorizationConfigurationImpl to enforce that the authenticated principal holds all required roles:
override val roleBasedAuthorizationConfiguration = RoleBasedAuthorizationConfigurationImpl(
enabled = true,
requiredRolesAllOf = setOf("ADMIN", "WRITE_GREETINGS")
)Your principal must implement PrincipalRoles so the library can inspect its roles:
data class UserPrincipal(
val userId: String,
override val roles: Set<String>
) : Principal, PrincipalRolesktor2-server-bind supports declarative validation of request bodies. You can define validation rules in your RouteConfig using a Multiplatform-friendly validation library (e.g., Konform).
object CreateGreeting : PostRouteConfig<GreetingRequest> {
// ...
override val validation = Validation {
GreetingRequest::message {
minLength(5)
}
}
}The library automatically bridges your RouteConfig.validation to Ktor's RequestValidation plugin when you call install() on your controller or route processor.
Register the predefined exception handler in Ktor's StatusPages plugin to automatically map validation failures to 400 Bad Request responses with structured error messages:
install(StatusPages) {
predefinedBadRequestExceptionsHandler()
}Install the predefined bad-request exception handler inside Ktor's StatusPages plugin to automatically respond 400 Bad Request when required parameters or headers are missing or cannot be converted:
install(StatusPages) {
predefinedBadRequestExceptionsHandler()
}This handles:
MissingRequestParameterException — a required query or path parameter is absentParameterConversionException — a parameter value cannot be converted to the target typeMissingHeaderException — a required header is absentBindValidationException — a request body fails validation (returns structured errors)You can supply a custom handler builder to override the default behavior:
install(StatusPages) {
predefinedBadRequestExceptionsHandler(
predefinedBadExceptionsHandlerBuilder = ExceptionHandling.defaultPredefinedBadExceptionsHandlerBuilder
)
}ktor2-server-bind ships a companion KSP annotation processor, ktor2-server-bind-processor, that inspects your controllers at compile time and writes an openapi.json resource file to the build output — no reflection, no runtime overhead.
Apply the KSP plugin and add the processor as a ksp dependency alongside the main library:
// build.gradle.kts
plugins {
id("com.google.devtools.ksp") version "<ksp-version>"
}
dependencies {
implementation("io.withlambda:ktor2-server-bind:<version>")
ksp("io.withlambda:ktor2-server-bind-processor:<version>")
}Mark each controller class with @ApiController (use tag to group endpoints in the spec) and each RouteProcessor property with @ApiEndpoint:
@ApiController(tag = "Greetings")
interface GreetingController : Controller {
@ApiEndpoint(path = "/greetings/{name}", summary = "Create a greeting")
val createGreeting: CreateGreeting.RouteProcessorImpl
}After the next build, openapi.json is written to the resources output directory and is available on the classpath. Serve it with the built-in OpenApiRoute:
routing {
openApiRoute() // GET /openapi.json
}ktor2-server-bind is an ideal foundation for building a Ktor server generator for the OpenAPI Generator project, enabling a fully spec-first (design-first) workflow for Ktor APIs.
In a spec-first approach you write your OpenAPI specification (openapi.yaml) before writing any code. A code generator then reads that specification and produces:
RouteConfig objects — one per operation, fully typed with the path, HTTP method, content types, path/query parameters, request body, and response models derived directly from the spec.@Serializable annotations, matching the spec's components/schemas.Because ktor2-server-bind already separates the shape of an endpoint (RouteConfig) from its behavior (RouteProcessor), the boundary between generated and handwritten code is clean: the generator owns the interfaces and configs, you own the implementations.
| OpenAPI concept |
ktor2-server-bind equivalent |
|---|---|
Operation (operationId) |
RouteConfig object + RouteProcessor implementation |
| Tag |
Controller interface grouping related RouteProcessors |
parameters (path, query, header) |
Typed PathParameters, RequiredQueryParameters, RequestHeaders inner classes |
requestBody |
Typed body extracted via receive<T>() in prepareRequestData()
|
responses |
Typed ResponseData / ResponseDataWithBody return values |
security |
AuthenticationConfiguration + RoleBasedAuthorizationConfiguration
|
Given an OpenAPI spec with:
paths:
/pets:
post:
operationId: createPet
tags: [Pets]
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/NewPet'
responses:
'201':
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'A Ktor generator built on ktor2-server-bind would emit:
// Generated — do not edit
object CreatePet : PostRouteConfig {
class RequestDataImpl(
override val pathParameter: Nothing? = null,
override val optionalQueryParameter: Nothing? = null,
override val requiredQueryParameter: Nothing? = null,
override val headers: Nothing? = null,
override val requestBody: NewPet
) : RequestWithBodyData<NewPet>
class ResponseDataImpl(
override val httpStatusCode: HttpStatusCode,
override val responseBody: Pet?,
override val responseMessage: String?,
override val responseHeaders: Nothing? = null
) : ResponseDataWithBody<Pet>
override val requestMapping = PostRequestMapping(
name = "createPet",
path = "/pets",
produces = ContentType.Application.Json,
consumes = ContentType.Application.Json
)
// ... conversionService, roleBasedAuthorizationConfiguration, parameter extractors
}
// Generated — do not edit
interface PetsController : Controller {
val createPet: CreatePet.RouteProcessorImpl
override val endpoints get() = listOf(createPet)
}You then implement only the business logic:
// Handwritten — your code
object PetsControllerImpl : PetsController {
override val authenticationConfiguration = AUTHENTICATION_CONFIGURATION_DEFAULT
override val createPet = CreatePet.RouteProcessorImpl { requestData ->
val saved = petService.save(requestData.requestBody)
CreatePet.ResponseDataImpl(HttpStatusCode.Created, saved, null)
}
}If you are interested in contributing a kotlin-ktor-server generator template to the OpenAPI Generator project, ktor2-server-bind provides all the runtime primitives the generated code needs — no additional runtime dependencies required beyond Ktor itself. See the OpenAPI Generator contribution guide for how to add a new server generator.
The build is pre-configured to publish to Maven Central via OSSRH (Sonatype OSS Repository Hosting).
For full instructions — what OSSRH is, how to get and configure credentials, GPG signing setup, local publishing steps, and a pre-release checklist — see PUBLISHING.md.
A GitHub Actions workflow is also provided at .github/workflows/publish.yml. Trigger it manually from the Actions tab, choose snapshot or release, and the pipeline handles the rest (signing included for releases).
For instructions on how to contribute to the project, including environment setup, code style (ktlint/detekt), and running tests, please see CONTRIBUTE.md.
Copyright 2024 withLambda
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.