Building REST APIs with Ktor and Kotlin: Async from the Ground Up with Coroutines

Programming tutorial - IT technology blog
Programming tutorial - IT technology blog

Quick Start: Ktor Running in 5 Minutes

If you’ve spent time fighting Spring Boot’s auto-configuration — or just watched the IDE spin for 15 seconds while the application context loads — Ktor is a breath of fresh air. It doesn’t do things behind your back.

Head to start.ktor.io and generate a new project. Select these plugins:

  • Routing
  • Content Negotiation
  • kotlinx.serialization
  • Netty (as the engine)

Your build.gradle.kts will look like this:

plugins {
    kotlin("jvm") version "1.9.22"
    kotlin("plugin.serialization") version "1.9.22"
    id("io.ktor.plugin") version "2.3.9"
    application
}

dependencies {
    implementation("io.ktor:ktor-server-core-jvm:2.3.9")
    implementation("io.ktor:ktor-server-netty-jvm:2.3.9")
    implementation("io.ktor:ktor-server-content-negotiation-jvm:2.3.9")
    implementation("io.ktor:ktor-serialization-kotlinx-json-jvm:2.3.9")
    implementation("ch.qos.logback:logback-classic:1.4.14")
    testImplementation("io.ktor:ktor-server-test-host-jvm:2.3.9")
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit:1.9.22")
}

application {
    mainClass.set("com.example.ApplicationKt")
}

Now create src/main/kotlin/com/example/Application.kt:

package com.example

import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.routing.*
import io.ktor.server.response.*
import kotlinx.serialization.Serializable

@Serializable
data class ServerInfo(val name: String, val version: String)

fun main() {
    embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}

fun Application.module() {
    install(ContentNegotiation) {
        json()
    }
    routing {
        get("/") {
            call.respond(ServerInfo("My Ktor API", "1.0.0"))
        }
    }
}

Run with ./gradlew run and hit http://localhost:8080. You get back:

{"name":"My Ktor API","version":"1.0.0"}

No XML. No annotations scanning the entire classpath. No magic. Just code you can read top to bottom.

Inside Ktor: Coroutines, Routing, and Content Negotiation

How Coroutines Actually Handle Concurrency

Traditional servlet-based frameworks assign one thread per request. Under heavy load, threads pile up, memory spikes, and latency climbs. Spring WebFlux addressed this with reactive streams, but the programming model — operators like flatMap, switchIfEmpty, backpressure management — carries a steep learning curve that slows down most teams.

Ktor takes a different route. Every handler is a suspend function. When it waits for a database query or an HTTP call, the coroutine suspends and the underlying thread is freed for other work. When the result arrives, the coroutine picks up exactly where it left off. The code reads like sequential logic — no callback chains, no reactive operators to debug.

routing {
    get("/users/{id}") {
        val id = call.parameters["id"]?.toIntOrNull()
            ?: return@get call.respond(HttpStatusCode.BadRequest, "Invalid ID")

        // This suspends the coroutine without blocking any thread
        val user = userRepository.findById(id)
            ?: return@get call.respond(HttpStatusCode.NotFound, "User not found")

        call.respond(user)
    }
}

Handling thousands of concurrent requests without spinning up thousands of threads is one of those things that sounds simple until you actually try it on the JVM. Ktor makes coroutine-based concurrency the default from day one — you don’t opt into it, you don’t wire it up separately. It’s just how the framework works.

Content Negotiation in Practice

The ContentNegotiation plugin reads the Accept header on incoming requests and the Content-Type on responses, then picks the right serializer. Configure it once — every call.respond() call handles conversion automatically from that point.

install(ContentNegotiation) {
    json(Json {
        prettyPrint = false
        ignoreUnknownKeys = true
        isLenient = true
    })
}

Parsing a POST body is just as clean:

@Serializable
data class CreateUserRequest(val username: String, val email: String)

@Serializable
data class UserResponse(val id: Int, val username: String, val email: String)

routing {
    post("/users") {
        val request = call.receive<CreateUserRequest>()
        val created = userRepository.create(request.username, request.email)
        call.respond(HttpStatusCode.Created, UserResponse(created.id, created.username, created.email))
    }
}

The @Serializable annotation from kotlinx.serialization generates serialization code at compile time — no runtime reflection, no Jackson magic, faster startup.

Structuring Routes for Real Applications

Putting everything in one routing block is fine for a demo. Add ten endpoints and it quickly becomes hard to navigate. Ktor’s routing DSL is built around extension functions on Route, so each feature stays self-contained in its own file:

fun Application.configureRouting() {
    routing {
        route("/api/v1") {
            userRoutes()
            articleRoutes()
        }
    }
}

fun Route.userRoutes() {
    route("/users") {
        get { /* list users */ }
        post { /* create user */ }
        route("/{id}") {
            get { /* get user */ }
            put { /* update user */ }
            delete { /* delete user */ }
        }
    }
}

Each feature lives in its own file and extension function. No central controller registry to update when you add a new module.

Advanced Usage: Plugins, Auth, and Error Handling

Consistent Error Responses with StatusPages

By default, an uncaught exception gives callers a bare 500 — no error message, no JSON body. The StatusPages plugin fixes that by mapping exception types to structured responses application-wide:

// Add dependency: ktor-server-status-pages-jvm
install(StatusPages) {
    exception<IllegalArgumentException> { call, cause ->
        call.respond(
            HttpStatusCode.BadRequest,
            mapOf("error" to (cause.message ?: "Bad request"))
        )
    }
    exception<NotFoundException> { call, cause ->
        call.respond(
            HttpStatusCode.NotFound,
            mapOf("error" to (cause.message ?: "Resource not found"))
        )
    }
}

JWT Authentication

Add the auth dependencies to your build file:

implementation("io.ktor:ktor-server-auth-jvm:2.3.9")
implementation("io.ktor:ktor-server-auth-jwt-jvm:2.3.9")
implementation("com.auth0:java-jwt:4.4.0")

Then configure it in your module() function:

install(Authentication) {
    jwt("auth-jwt") {
        realm = "my-api"
        verifier(
            JWT.require(Algorithm.HMAC256(jwtSecret))
                .withAudience(jwtAudience)
                .withIssuer(jwtIssuer)
                .build()
        )
        validate { credential ->
            if (credential.payload.audience.contains(jwtAudience))
                JWTPrincipal(credential.payload)
            else null
        }
    }
}

// Wrap protected routes:
authenticate("auth-jwt") {
    get("/me") {
        val principal = call.principal<JWTPrincipal>()
        call.respond(mapOf("userId" to principal?.payload?.subject))
    }
}

Coroutine-Friendly Database Access

JDBC drivers are blocking by design. Running them directly in a Ktor coroutine blocks the shared thread pool. The fix is withContext(Dispatchers.IO), which moves blocking work to a dedicated IO thread pool without blocking the coroutine dispatcher Ktor uses for routing:

suspend fun findUserById(id: Int): User? = withContext(Dispatchers.IO) {
    // Blocking JDBC call runs here on the IO dispatcher
    transaction {
        Users.select { Users.id eq id }
            .map { User(it[Users.id].value, it[Users.username]) }
            .singleOrNull()
    }
}

// Caller code looks clean:
routing {
    get("/users/{id}") {
        val id = call.parameters["id"]!!.toInt()
        val user = findUserById(id) ?: return@get call.respond(HttpStatusCode.NotFound)
        call.respond(user)
    }
}

Practical Tips Before You Ship

Test Without Starting a Real Server

Ktor’s testApplication runs your full application in-memory — no ports, no open sockets, test setup under 100ms:

class ApplicationTest {
    @Test
    fun testRoot() = testApplication {
        application { module() }
        val response = client.get("/")
        assertEquals(HttpStatusCode.OK, response.status)
    }

    @Test
    fun testCreateUser() = testApplication {
        application { module() }
        val response = client.post("/users") {
            contentType(ContentType.Application.Json)
            setBody("""{"username":"alice","email":"[email protected]"}""")
        }
        assertEquals(HttpStatusCode.Created, response.status)
    }
}

Manage Configuration with HOCON

Keep secrets out of code. Ktor supports HOCON config files natively via src/main/resources/application.conf:

ktor {
    deployment {
        port = 8080
        port = ${?PORT}
    }
}

jwt {
    secret = ${?JWT_SECRET}
    issuer = "https://api.example.com"
    audience = "api-users"
}

Access it inside your module:

val jwtSecret = environment.config.property("jwt.secret").getString()

Deploying to Production

Build a self-contained fat JAR and ship it anywhere Java runs:

# Build
./gradlew buildFatJar

# Run directly
java -jar build/libs/my-api-all.jar

# Or containerize it
docker build -t my-ktor-api .
docker run -p 8080:8080 -e JWT_SECRET=supersecret my-ktor-api

The resulting JAR sits between 15–25 MB. Cold start on a modest VPS is around 1–2 seconds — compare that to 5–12 seconds for a typical Spring Boot application on the same hardware.

Ktor isn’t a Spring replacement. For large enterprise codebases with years of investment in that ecosystem, the switching cost makes no sense. But for a new service or microservice — especially if you want to understand exactly what happens at each step — Ktor with Kotlin coroutines is a genuinely clean option. The code looks sequential, handles real load, and tests in milliseconds. That combination is rarer on the JVM than it should be.

Share: