Extensions

Add CORS, Bearer parsing, validation, OpenAPI, access logging or OpenTelemetry.

ktServe extensions

Build your server.
Choose its modules.

Start with the standalone HTTP server. Add only the modules your service uses, then activate each one in your Kotlin code.

Example API build
  • Validationinstall(validation())
  • OpenAPIinstall(openApi(…))
ktServe coreHTTP · routing · streaming

CORS, Bearer, access logging and tracing are left out of this build.

Install the source preview

Add the ktServe checkout as a Gradle included build. Use JDK 21, Kotlin 2.4.21 and Maven Central for this preview.

The modules target standalone HTTP/1.1. Native support covers Linux x86-64, Linux ARM64 and Apple Silicon macOS.

Each guide shows the dependency to put inside your app’s dependencies block. Kotlin Multiplatform apps can put Native-compatible modules in commonMain.dependencies and OpenTelemetry in jvmMain.dependencies.

For a local macOS Native build, run Gradle with -Pbenchmark.targetOs=macos.

In your app’s project directory
git clone --depth 1 https://github.com/christian-draeger/ktserve.git
settings.gradle.kts
includeBuild("ktserve/components/ktserve/extensions")
build.gradle.kts
repositories { mavenCentral() }

The included build resolves the preview module and its matching ktServe core. Use the examples below with the 0.0.0-dev source version.

JVM + Native

CORS

Allow a browser frontend running on a different origin to call your API. The extension handles preflights and adds the matching CORS headers to responses.

List allowed origins, methods and headers. Install CORS before extensions that can return a response early.

CORS configuration
Gradle dependency
implementation("codes.draeger:ktserve-cors:0.0.0-dev")
Allow a frontend origin
import codes.draeger.ktserve.*
import codes.draeger.ktserve.cors.*

fun main() = serve {
    install(cors {
        allowOrigins("https://app.example")
        allowMethods("GET")
        allowHeaders("Authorization")
    })
    get("/status") { text("ok") }
}
JVM + Native

Bearer

Read Bearer credentials from the Authorization header without repeating the parsing in every handler. The extension distinguishes absent, malformed and present credentials.

Connect the parsed token to your own verifier. Your app decides who gets access and how to return a challenge.

Bearer credential states
Gradle dependency
implementation("codes.draeger:ktserve-bearer:0.0.0-dev")
Verify a token in your app
import codes.draeger.ktserve.*
import codes.draeger.ktserve.bearer.*

fun serveAccounts(verify: suspend (String) -> Boolean) =
    serve {
        install(bearer())

        getSuspending("/account") { request ->
            val credential = request.bearerCredential
            if (credential is BearerCredential.Present
                && verify(credential.token)
            ) {
                text("ok")
            } else {
                text("Unauthorized", status = 401)
                    .withHeaders(HttpField("WWW-Authenticate", "Bearer"))
            }
        }
    }
JVM + Native

Validation

Check decoded JSON against Konform rules before a typed handler runs. Invalid input gets a 422 Problem Details response with pointers to the affected fields.

Declare shared rules on the request type. Schema-aware rules such as minLength also appear in generated OpenAPI.

Apply kotlin("plugin.serialization") version "2.4.21" to use @Serializable models.

Validation rules and overrides
Gradle dependency
implementation("codes.draeger:ktserve-validation:0.0.0-dev")
Validate a typed request
import codes.draeger.ktserve.*
import codes.draeger.ktserve.validation.*
import kotlinx.serialization.Serializable

@Serializable
@ValidateWith(CreateUser.Rules::class)
data class CreateUser(val name: String) {
    object Rules : KonformRules<CreateUser> by rules({
        minLength(CreateUser::name, 2)
    })
}

fun main() = serve {
    install(validation())
    api("/api") {
        post("/users", status = 201) { input: CreateUser -> input }
    }
}
JVM + Native

OpenAPI

Generate an OpenAPI 3.1 document from typed routes and their serializers at startup. Status codes, media types, body types and available validation rules come from the registered route.

Serve the document with serveAt or export it through onDocument. Add explicit operations to describe manually constructed responses.

Apply the Kotlin Serialization plugin for your @Serializable models.

OpenAPI export and schema overrides
Gradle dependency
implementation("codes.draeger:ktserve-openapi:0.0.0-dev")
Expose the generated contract
import codes.draeger.ktserve.*
import codes.draeger.ktserve.openapi.*
import kotlinx.serialization.Serializable

@Serializable
data class User(val id: Int, val name: String)

fun main() = serve {
    install(openApi(title = "Users", version = "1.0.0") {
        serveAt("/openapi.json")
    })
    api("/api") {
        get("/users/me") { User(42, "Ada") }
    }
}
JVM + Native

Access logging

Record the HTTP method, status, duration and outcome of each exchange. The default writer sends batched lines to stderr.

Send structured events to your own logging backend with accessLog { event -> … }. Bounded buffers report dropped events if the writer falls behind.

Structured logging and JVM logging backends
Gradle dependency
implementation("codes.draeger:ktserve-access-log:0.0.0-dev")
Log HTTP exchanges to stderr
import codes.draeger.ktserve.*
import codes.draeger.ktserve.accesslog.*

fun main() = serve {
    install(accessLog())
    get("/health") { text("ok") }
}
JVM

OpenTelemetry

Trace an HTTP exchange from its incoming headers through completion. Spans record the HTTP method, matched route template, status and terminal errors.

Pass in the OpenTelemetry instance your application configures. Your SDK controls trace context propagation, sampling and the exporter.

Configure an SDK and batch exporter
Gradle dependency · JVM
implementation("codes.draeger:ktserve-opentelemetry:0.0.0-dev")
Use your configured telemetry instance
import codes.draeger.ktserve.*
import codes.draeger.ktserve.opentelemetry.*
import io.opentelemetry.api.OpenTelemetry

fun serveTraced(telemetry: OpenTelemetry) = serve {
    install(openTelemetry(telemetry))
    get("/health") { text("ok") }
}

Try validation and OpenAPI together

Use the downloadable CLI to run a typed API from Kotlin source. The example returns JSON, rejects invalid input and exposes its OpenAPI contract.

Run the typed API example