HTTP with Ktor

suggest change

Ktor is JetBrains' framework for HTTP in Kotlin. It has two halves that share types and conventions:

Both are built from plugins. The core is small, and features such as JSON, compression, logging, retries or authentication are plugins you install().

This article covers the basics of both sides:

Designing a full REST API (resources, validation, versioning) is covered in REST APIs. For other JVM HTTP clients (OkHttp, java.net.http) see HTTP client.

All examples were compiled with Kotlin 2.4.21 and Ktor 3.6.0, and run on JDK 25. Each program starts a server and then calls it with the Ktor client from the same process, so you can run it as-is.

Dependencies

plugins {
    kotlin("jvm") version "2.4.21"
    kotlin("plugin.serialization") version "2.4.21" // for @Serializable classes
}

val ktorVersion = "3.6.0"

dependencies {
    // server
    implementation("io.ktor:ktor-server-netty:$ktorVersion")
    implementation("io.ktor:ktor-server-content-negotiation:$ktorVersion")
    implementation("io.ktor:ktor-server-status-pages:$ktorVersion")
    implementation("io.ktor:ktor-server-call-logging:$ktorVersion")

    // client
    implementation("io.ktor:ktor-client-cio:$ktorVersion")
    implementation("io.ktor:ktor-client-content-negotiation:$ktorVersion")
    implementation("io.ktor:ktor-client-logging:$ktorVersion")

    // JSON for both sides
    implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")

    // Ktor logs through SLF4J; pick a backend
    implementation("org.slf4j:slf4j-simple:2.0.17")

    testImplementation("io.ktor:ktor-server-test-host:$ktorVersion")
    testImplementation(kotlin("test"))
}

Ktor is split into many small artifacts, one per plugin. If an import doesn't resolve, the plugin's artifact is usually missing.

Server engines and client engines are separate choices:

Side Engine Notes
server Netty the most used, battle-tested
server CIO pure Kotlin coroutines, no extra dependencies
server Jetty, Tomcat if you need a servlet container
client CIO pure Kotlin, works on JVM, Android and Native
client OkHttp, Java, Apache5 wrap existing JVM clients
client Darwin, Js, WinHttp, Curl for iOS, browsers and Native

Your application code doesn't depend on the engine. Switching is a one-line change.

Hello, Ktor

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking

fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                call.respondText("Hello from Ktor!")
            }
        }
    }.start(wait = false)

    runBlocking {
        HttpClient(CIO).use { client ->
            val response = client.get("http://localhost:8080/")
            println(response.status)
            println(response.headers["Content-Type"])
            println(response.bodyAsText())
        }
    }
    server.stop(gracePeriodMillis = 100, timeoutMillis = 500)
}

Output:

[main] INFO io.ktor.server.Application - Autoreload is disabled because the development mode is off.
[main] INFO io.ktor.server.Application - Application started in 0.111 seconds.
[DefaultDispatcher-worker-1] INFO io.ktor.server.Application - Responding at http://127.0.0.1:8080
200 OK
text/plain; charset=UTF-8
Hello from Ktor!

Things to note:

Routing

Routes match an HTTP method and a path. Paths can contain parameters in braces, and route() groups routes under a common prefix:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.delete
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import io.ktor.client.statement.request
import io.ktor.http.HttpStatusCode
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.request.header
import io.ktor.server.request.receiveText
import io.ktor.server.response.header
import io.ktor.server.response.respond
import io.ktor.server.response.respondRedirect
import io.ktor.server.response.respondText
import io.ktor.server.routing.delete
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking

val notes = mutableMapOf(1 to "buy milk", 2 to "call mom")

fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        routing {
            get("/hello/{name}") {
                val name = call.parameters["name"]
                val times = call.request.queryParameters["times"]?.toIntOrNull() ?: 1
                call.respondText("Hello, $name! ".repeat(times).trim())
            }
            route("/notes") {
                get {
                    call.respondText(notes.entries.joinToString("\n") { "${it.key}: ${it.value}" })
                }
                get("/{id}") {
                    val id = call.parameters["id"]?.toIntOrNull()
                    val note = notes[id]
                    if (note == null) {
                        call.respondText("no note $id", status = HttpStatusCode.NotFound)
                    } else {
                        call.respondText(note)
                    }
                }
                post {
                    val text = call.receiveText()
                    val id = (notes.keys.maxOrNull() ?: 0) + 1
                    notes[id] = text
                    call.response.header("Location", "/notes/$id")
                    call.respondText("created $id", status = HttpStatusCode.Created)
                }
                delete("/{id}") {
                    val id = call.parameters["id"]!!.toInt()
                    notes.remove(id)
                    call.respond(HttpStatusCode.NoContent)
                }
            }
            get("/whoami") {
                val agent = call.request.header("User-Agent") ?: "unknown"
                call.respondText("you are $agent")
            }
            get("/old") {
                call.respondRedirect("/hello/redirected")
            }
        }
    }.start(wait = false)

    runBlocking {
        HttpClient(CIO).use { client ->
            val base = "http://localhost:8080"
            suspend fun show(r: HttpResponse) =
                println("${r.request.method.value} ${r.request.url.encodedPath} -> ${r.status.value} ${r.bodyAsText()}")

            show(client.get("$base/hello/Kotlin?times=2"))
            show(client.get("$base/notes/1"))
            show(client.get("$base/notes/42"))
            val created = client.post("$base/notes") { setBody("write article") }
            show(created)
            println("Location: ${created.headers["Location"]}")
            show(client.delete("$base/notes/2"))
            show(client.get("$base/notes"))
            show(client.get("$base/whoami") { header("User-Agent", "my-app/1.0") })
            show(client.get("$base/old"))
        }
    }
    server.stop(100, 500)
}

Output:

GET /hello/Kotlin -> 200 Hello, Kotlin! Hello, Kotlin!
GET /notes/1 -> 200 buy milk
GET /notes/42 -> 404 no note 42
POST /notes -> 201 created 3
Location: /notes/3
DELETE /notes/2 -> 204
GET /notes -> 200 1: buy milk
3: write article
GET /whoami -> 200 you are my-app/1.0
GET /hello/redirected -> 200 Hello, redirected!

The building blocks:

Task Server code
path parameter /{id} call.parameters["id"]
query parameter ?times=2 call.request.queryParameters["times"]
request header call.request.header("User-Agent") or call.request.headers[...]
raw body call.receiveText(), call.receive<ByteArray>(), call.receiveChannel()
form body call.receiveParameters()
response with status call.respondText(text, status = HttpStatusCode.Created)
status only call.respond(HttpStatusCode.NoContent)
response header call.response.header("Location", "/notes/3")
redirect call.respondRedirect("/new") (302; permanent = true gives 301)

Parameters are always strings. toIntOrNull() and the Elvis operator turn missing or bad values into a 404 or a default instead of an exception.

Path patterns also support optional parameters ({id?}), wildcards (*) and tail matches ({path...}, read with call.parameters.getAll("path")).

On the client side, note that the Ktor client follows redirects by default: the last request ended at /hello/redirected. Set followRedirects = false in the client config to see the 302 instead.

JSON with ContentNegotiation

The ContentNegotiation plugin converts between Kotlin objects and request/response bodies. It exists on both sides with the same name, so import one under an alias when you use both in a file:

import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.Serializable
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation as ClientContentNegotiation
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation as ServerContentNegotiation

@Serializable
data class Order(val item: String, val quantity: Int)

@Serializable
data class Receipt(val id: Int, val item: String, val quantity: Int, val total: Double)

fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        install(ServerContentNegotiation) {
            json()
        }
        routing {
            post("/orders") {
                val order = call.receive<Order>()
                call.respond(Receipt(id = 1, item = order.item, quantity = order.quantity, total = order.quantity * 2.5))
            }
            get("/prices") {
                call.respond(mapOf("apple" to 2.5, "pear" to 3.0))
            }
        }
    }.start(wait = false)

    runBlocking {
        val client = HttpClient(CIO) {
            install(ClientContentNegotiation) {
                json()
            }
        }
        client.use {
            val response = client.post("http://localhost:8080/orders") {
                contentType(ContentType.Application.Json)
                setBody(Order("apple", 4))
            }
            println(response.bodyAsText())
            val receipt: Receipt = response.body()
            println(receipt)

            val prices = client.get("http://localhost:8080/prices").body<Map<String, Double>>()
            println(prices)
        }
    }
    server.stop(100, 500)
}

Output:

{"id":1,"item":"apple","quantity":4,"total":10.0}
Receipt(id=1, item=apple, quantity=4, total=10.0)
{apple=2.5, pear=3.0}

Handling errors

On the server: StatusPages

Without extra setup, an uncaught exception in a handler becomes a 500 Internal Server Error. Ktor maps a few of its own exceptions to proper codes: NotFoundException to 404, BadRequestException to 400, and so on.

The StatusPages plugin lets you map your own exceptions and status codes to responses in one place, instead of wrapping every handler in try/catch:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.plugins.ServerResponseException
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.BadRequestException
import io.ktor.server.plugins.NotFoundException
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking

class OutOfStockException(val item: String) : RuntimeException("$item is out of stock")

fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        install(StatusPages) {
            exception<OutOfStockException> { call, cause ->
                call.respondText(cause.message!!, status = HttpStatusCode.Conflict)
            }
            exception<BadRequestException> { call, cause ->
                call.respondText("bad request: ${cause.message}", status = HttpStatusCode.BadRequest)
            }
            exception<NotFoundException> { call, cause ->
                call.respondText("not found: ${cause.message}", status = HttpStatusCode.NotFound)
            }
            exception<Throwable> { call, cause ->
                call.application.environment.log.error("unhandled: $cause")
                call.respondText("internal error", status = HttpStatusCode.InternalServerError)
            }
            status(HttpStatusCode.NotFound) { call, status ->
                call.respondText("nothing at ${call.request.local.uri}", status = status)
            }
        }
        routing {
            get("/stock/{item}") {
                val item = call.parameters["item"]!!
                when (item) {
                    "apple" -> call.respondText("12 left")
                    "pear" -> throw OutOfStockException(item)
                    "kiwi" -> throw NotFoundException("no such item: $item")
                    "bad" -> throw BadRequestException("bad item name")
                    else -> error("database is down")
                }
            }
        }
    }.start(wait = false)

    runBlocking {
        HttpClient(CIO).use { client ->
            for (path in listOf("/stock/apple", "/stock/pear", "/stock/kiwi", "/stock/bad", "/stock/plum", "/nope")) {
                val r = client.get("http://localhost:8080$path")
                println("$path -> ${r.status.value} ${r.bodyAsText()}")
            }
        }

        // with expectSuccess = true non-2xx responses throw
        val strict = HttpClient(CIO) { expectSuccess = true }
        for (path in listOf("/stock/pear", "/stock/plum")) {
            try {
                strict.get("http://localhost:8080$path")
            } catch (e: ClientRequestException) {      // 4xx
                println("client error ${e.response.status}: ${e.response.bodyAsText()}")
            } catch (e: ServerResponseException) {     // 5xx
                println("server error ${e.response.status}")
            }
        }
        strict.close()
    }
    server.stop(100, 500)
}

Output:

/stock/apple -> 200 12 left
/stock/pear -> 409 pear is out of stock
/stock/kiwi -> 404 not found: no such item: kiwi
/stock/bad -> 400 bad request: bad item name
[eventLoopGroupProxy-4-5] ERROR io.ktor.server.Application - unhandled: java.lang.IllegalStateException: database is down
/stock/plum -> 500 internal error
/nope -> 404 nothing at /nope
client error 409 Conflict: pear is out of stock
[eventLoopGroupProxy-4-8] ERROR io.ktor.server.Application - unhandled: java.lang.IllegalStateException: database is down
server error 500 Internal Server Error

How it works:

On the client: status codes and expectSuccess

By default the Ktor client does not throw on 4xx or 5xx. You get an HttpResponse and check response.status yourself, as the first loop does.

With expectSuccess = true, non-2xx responses throw:

All three extend ResponseException, which gives you the response to inspect. Network failures throw other exceptions, such as java.net.ConnectException or HttpRequestTimeoutException.

Configuring the client

Most client features are plugins too. The HttpClient(CIO) { ... } block is where you set defaults shared by all requests:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.HttpRequestRetry
import io.ktor.client.plugins.HttpRequestTimeoutException
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.plugins.timeout
import io.ktor.client.request.forms.submitForm
import io.ktor.client.request.get
import io.ktor.client.request.parameter
import io.ktor.client.statement.bodyAsText
import io.ktor.http.HttpStatusCode
import io.ktor.http.parameters
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.request.receiveParameters
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicInteger
import kotlin.time.measureTimedValue

fun startServer() = embeddedServer(Netty, port = 8080) {
    val attempts = AtomicInteger()
    routing {
        get("/api/search") {
            val q = call.request.queryParameters
            call.respondText("q=${q["q"]} page=${q["page"]} key=${call.request.headers["X-Api-Key"]}")
        }
        post("/api/login") {
            val form = call.receiveParameters()
            call.respondText("welcome ${form["user"]}")
        }
        get("/api/slow") {
            delay(call.request.queryParameters["ms"]!!.toLong())
            call.respondText("done")
        }
        get("/api/flaky") {
            if (attempts.incrementAndGet() < 3) {
                call.respondText("try again", status = HttpStatusCode.ServiceUnavailable)
            } else {
                call.respondText("ok after ${attempts.get()} attempts")
            }
        }
    }
}.start(wait = false)

fun main() {
    val server = startServer()
    val client = HttpClient(CIO) {
        defaultRequest {
            url("http://localhost:8080/api/")
            headers.append("X-Api-Key", "secret-123")
        }
        install(HttpTimeout) {
            requestTimeoutMillis = 2_000
            connectTimeoutMillis = 1_000
        }
        install(HttpRequestRetry) {
            retryOnServerErrors(maxRetries = 3)
            exponentialDelay(baseDelayMs = 100, maxDelayMs = 1_000) // ~200ms, ~400ms, ...
        }
    }

    runBlocking {
        // relative URL + query parameters (properly encoded)
        println(client.get("search") {
            parameter("q", "kotlin & ktor")
            parameter("page", 2)
        }.bodyAsText())

        // application/x-www-form-urlencoded POST
        println(client.submitForm("login", formParameters = parameters {
            append("user", "alice")
            append("password", "s3cret")
        }).bodyAsText())

        // retried automatically on 503
        println(client.get("flaky").bodyAsText())

        // per-request timeout overrides the default
        try {
            client.get("slow?ms=1000") { timeout { requestTimeoutMillis = 300 } }
        } catch (e: HttpRequestTimeoutException) {
            println("timeout: ${e.message}")
        }

        // concurrent requests: total time ~ slowest request, not the sum
        val (bodies, took) = measureTimedValue {
            listOf(300, 200, 100).map { ms ->
                async { client.get("slow?ms=$ms").bodyAsText() }
            }.awaitAll()
        }
        println("$bodies in ${took.inWholeMilliseconds / 100 * 100}+ ms")
    }
    client.close()
    server.stop(1_000, 2_000)
}

Output:

q=kotlin & ktor page=2 key=secret-123
welcome alice
ok after 3 attempts
timeout: Request timeout has expired [url=http://localhost:8080/api/slow?ms=1000, request_timeout=300 ms]
[done, done, done] in 300+ ms

What each piece does:

The client is thread-safe. Share one instance across your application, for example through dependency injection or a top-level val.

Streaming large bodies

bodyAsText() and body<T>() load the whole response into memory. That's fine for API responses, but not for a 2 GB download. Use prepareGet(...).execute { } and read the body as a ByteReadChannel instead:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.request.prepareGet
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.contentLength
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.response.respondFile
import io.ktor.server.response.respondTextWriter
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import io.ktor.util.cio.writeChannel
import io.ktor.utils.io.copyAndClose
import io.ktor.utils.io.readUTF8Line
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.io.File
import kotlin.io.path.createTempFile

fun main() {
    val bigFile = createTempFile("data", ".bin").toFile().apply { writeBytes(ByteArray(5_000_000) { it.toByte() }) }

    val server = embeddedServer(Netty, port = 8080) {
        routing {
            get("/download") {
                call.respondFile(bigFile)
            }
            get("/events") {
                call.respondTextWriter(ContentType.Text.Plain) {
                    for (i in 1..3) {
                        write("event $i\n")
                        flush()          // send this chunk now
                        delay(200)
                    }
                }
            }
        }
    }.start(wait = false)

    runBlocking {
        HttpClient(CIO).use { client ->
            // stream a large body straight to disk without loading it into memory
            val target = File.createTempFile("copy", ".bin")
            client.prepareGet("http://localhost:8080/download").execute { response ->
                println("Content-Length: ${response.contentLength()}")
                val copied = response.bodyAsChannel().copyAndClose(target.writeChannel())
                println("copied $copied bytes, same content: ${target.readBytes().contentEquals(bigFile.readBytes())}")
            }

            // read a chunked response line by line as it arrives
            val start = System.currentTimeMillis()
            client.prepareGet("http://localhost:8080/events").execute { response ->
                println("Transfer-Encoding: ${response.headers[HttpHeaders.TransferEncoding]}")
                val channel = response.bodyAsChannel()
                while (true) {
                    val line = channel.readUTF8Line() ?: break
                    println("+${(System.currentTimeMillis() - start) / 100 * 100}ms $line")
                }
            }
            target.delete()
        }
    }
    bigFile.delete()
    server.stop(100, 500)
}

Output:

Content-Length: 5000000
copied 5000000 bytes, same content: true
Transfer-Encoding: chunked
+0ms event 1
+200ms event 2
+400ms event 3

For a standard way to push events to browsers, Ktor also has Server-Sent Events (ktor-server-sse) and WebSockets.

Structuring an application

Putting everything inside the embeddedServer lambda doesn't scale. The usual structure is:

import io.ktor.http.HttpStatusCode
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import io.ktor.server.routing.routing
import kotlinx.serialization.Serializable
import java.util.concurrent.ConcurrentHashMap

@Serializable
data class Todo(val id: Int = 0, val title: String, val done: Boolean = false)

class TodoRepository {
    private val todos = ConcurrentHashMap<Int, Todo>()
    private var nextId = 1
    fun all(): List<Todo> = todos.values.sortedBy { it.id }
    @Synchronized fun add(todo: Todo): Todo = todo.copy(id = nextId++).also { todos[it.id] = it }
}

// The application is an extension function on Application: the same code
// runs in production (embeddedServer) and in tests (testApplication).
fun Application.module(repo: TodoRepository = TodoRepository()) {
    install(ContentNegotiation) { json() }
    routing {
        get("/health") { call.respond(mapOf("status" to "up")) }
        todoRoutes(repo)
    }
}

// Group related routes in an extension function on Route.
fun Route.todoRoutes(repo: TodoRepository) {
    route("/todos") {
        get { call.respond(repo.all()) }
        post {
            val todo = repo.add(call.receive<Todo>())
            call.respond(HttpStatusCode.Created, todo)
        }
    }
}

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

Calling it with curl:

$ curl -i -X POST -H "Content-Type: application/json" -d '{"title":"buy milk"}' localhost:8080/todos
HTTP/1.1 201 Created
Content-Length: 40
Content-Type: application/json

{"id":1,"title":"buy milk","done":false}

$ curl localhost:8080/todos
[{"id":1,"title":"buy milk","done":false}]

$ curl -i -X POST -H "Content-Type: application/json" -d '{"name":"x"}' localhost:8080/todos
HTTP/1.1 400 Bad Request
Content-Length: 44
Content-Type: text/plain; charset=UTF-8

Failed to convert request body to class Todo

Notes:

Testing with testApplication

testApplication (from ktor-server-test-host) runs your module in memory, without opening a port. Its client sends requests straight into the server pipeline, so tests are fast and can run in parallel without port conflicts:

import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.testing.testApplication
import kotlin.test.Test
import kotlin.test.assertEquals
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation as ClientContentNegotiation

class AppTest {
    @Test
    fun health() = testApplication {
        application { module() }
        val response = client.get("/health")
        assertEquals(HttpStatusCode.OK, response.status)
        assertEquals("""{"status":"up"}""", response.bodyAsText())
    }

    @Test
    fun `create and list todos`() = testApplication {
        application { module(TodoRepository()) }
        val client = createClient {
            install(ClientContentNegotiation) { json() }
        }
        val created = client.post("/todos") {
            contentType(ContentType.Application.Json)
            setBody(Todo(title = "write tests"))
        }
        assertEquals(HttpStatusCode.Created, created.status)
        assertEquals(Todo(1, "write tests"), created.body<Todo>())

        val all = client.get("/todos").body<List<Todo>>()
        assertEquals(listOf("write tests"), all.map { it.title })
    }
}

Output of the JUnit console launcher:

├─ JUnit Jupiter ✔
│  └─ AppTest ✔
│     ├─ health() ✔
│     └─ create and list todos() ✔

Test run finished after 1366 ms
[         2 tests successful      ]
[         0 tests failed          ]

Logging requests

The client Logging plugin and the server CallLogging plugin show what goes over the wire:

import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.request.bearerAuth
import io.ktor.client.request.get
import io.ktor.http.HttpHeaders
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.calllogging.CallLogging
import io.ktor.server.request.httpMethod
import io.ktor.server.request.uri
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking

fun main() {
    val server = embeddedServer(Netty, port = 8080) {
        install(CallLogging) {
            format { call ->
                "${call.response.status()?.value} ${call.request.httpMethod.value} ${call.request.uri}"
            }
        }
        routing {
            get("/ping") { call.respondText("pong") }
        }
    }.start(wait = false)

    val client = HttpClient(CIO) {
        install(Logging) {
            logger = object : Logger {
                override fun log(message: String) = println("CLIENT: $message")
            }
            level = LogLevel.HEADERS
            sanitizeHeader { it == HttpHeaders.Authorization } // never log tokens
        }
    }
    runBlocking {
        client.get("http://localhost:8080/ping") { bearerAuth("my-secret-token") }
    }
    client.close()
    server.stop(100, 500)
}

Output (startup lines omitted, SLF4J at info level):

CLIENT: REQUEST: http://localhost:8080/ping
METHOD: GET
COMMON HEADERS
-> Accept: */*
-> Authorization: ***
CONTENT HEADERS
-> Content-Length: 0
[eventLoopGroupProxy-4-1] INFO io.ktor.server.Application - 200 GET /ping
CLIENT: RESPONSE: 200 OK
METHOD: GET
FROM: http://localhost:8080/ping
COMMON HEADERS
-> Content-Length: 4
-> Content-Type: text/plain; charset=UTF-8

For writing your own plugins (request timing, request IDs, API keys) see HTTP middleware. For headers in depth see HTTP headers, and for HTTPS see TLS and HTTPS.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents