Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 134 ยท Testing and Tooling

Building HTTP Servers and Clients with Ktor

Learn how Ktor builds HTTP servers and clients in Kotlin: modules, routing, content negotiation, error handling, the HttpClient and testing, with runnable plain-Kotlin demos.

Kotlin's most popular framework for web services is Ktor, built by JetBrains. It is small, asynchronous from the ground up (it is built on coroutines), and configured with the type-safe DSL techniques you saw in Type-Safe Builders. One library family gives you both sides of HTTP: a server that answers requests and a client that sends them.

This lesson explains the shape of a Ktor application and its main ideas: modules, routing, plugins such as content negotiation, error handling, the client, and testing. A word about the setup: the in-browser runner has no network access and no dependencies beyond the standard library, so the Ktor code below is read-only. To let you run something real, the two live examples build the same ideas with only the JDK's built-in HTTP server and client on the loopback address, using a tiny home-made routing DSL. The structure maps one-to-one onto Ktor.

The big picture

A request reaches an engine (Netty, CIO or Jetty), travels through installed plugins, is matched by routing against a path and method, and a handler writes the response. The client side is a mirror image: you build a request, send it, and read the response body.

flowchart LR
    C["Client<br/>HttpClient"] -->|"GET /books/1"| E["Engine<br/>Netty / CIO"]
    E --> P["Plugins<br/>content negotiation,<br/>status pages, auth"]
    P --> R["Routing<br/>match method + path"]
    R --> H["Handler<br/>call.respond(...)"]
    H -->|"200 JSON"| C

A Ktor server is an engine plus plugins plus routes. Everything is assembled in code with lambdas.

A minimal Ktor server (read-only)

A Ktor server is a function that configures an Application. By convention that function is called a module:

Kotlin
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

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

fun Application.module() {
    routing {
        get("/") {
            call.respondText("Hello from Ktor")
        }
    }
}

embeddedServer starts the engine on a port; wait = true keeps main alive. module is an extension function on Application, so you can split a big application into several modules (fun Application.users(), fun Application.orders()) and install each one. The handler lambda is a suspend block with call in scope: the ApplicationCall holds the request and the response. Because handlers are suspending functions, waiting for a database or another service does not block a thread.

The Gradle setup lists each feature as a separate dependency, for example ktor-server-core, ktor-server-netty, ktor-server-content-negotiation, ktor-serialization-kotlinx-json, and for tests ktor-server-test-host. Check the Ktor site for the current 3.x version numbers.

Routing

Routing is a tree of nested blocks that mirrors your URL structure. Path parameters are written in braces, and call.parameters reads them:

Kotlin
routing {
    route("/books") {
        get {                                     // GET /books
            call.respond(bookStore.all())
        }
        get("/{id}") {                            // GET /books/42
            val id = call.parameters["id"]?.toIntOrNull()
                ?: return@get call.respond(HttpStatusCode.BadRequest, "id must be a number")
            val book = bookStore.find(id)
                ?: return@get call.respond(HttpStatusCode.NotFound)
            call.respond(book)
        }
        post {                                    // POST /books
            val draft = call.receive<NewBook>()
            val saved = bookStore.add(draft)
            call.respond(HttpStatusCode.Created, saved)
        }
    }
}

Three things to notice. return@get leaves the handler early, the same labeled-return idea as in lambdas. Query parameters come from call.request.queryParameters["page"]. And call.receive<T>() converts the request body into a Kotlin object, which needs the plugin described below.

See the idea run

Here is the same shape, built with the JDK only. routing { get("/path") { ... } } is a lambda with receiver, exactly the technique Ktor uses; the handler returns a status and body instead of calling call.respond. The program starts a real server on the loopback address, sends four requests and prints the results:

Kotlin A tiny routing DSL on the JDK HTTP server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The 404 for /nope comes from the fallback in dispatch, just like Ktor returns 404 when no route matches. The port is chosen by the system (0), so the program does not clash with anything.

Content negotiation

APIs rarely return plain text. They return JSON, and sometimes other formats, chosen by what the caller asks for in the Accept header (and what the caller sends in Content-Type). Ktor packages this as the ContentNegotiation plugin, which uses a serialization library, usually kotlinx.serialization, to convert between Kotlin objects and bytes:

Kotlin
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.plugins.contentnegotiation.*
import kotlinx.serialization.Serializable

@Serializable
data class Book(val id: Int, val title: String)

@Serializable
data class NewBook(val title: String)

fun Application.module() {
    install(ContentNegotiation) {
        json()
    }
    routing {
        get("/books/1") {
            call.respond(Book(1, "Dune"))          // sent as {"id":1,"title":"Dune"}
        }
        post("/books") {
            val draft = call.receive<NewBook>()    // parsed from the JSON body
            call.respond(HttpStatusCode.Created, Book(3, draft.title))
        }
    }
}

call.respond(book) looks at the request's Accept header, finds a registered converter that matches, and writes the body with the right Content-Type. If the client asks for something the server cannot produce, Ktor answers with a 406 or 415 status instead of guessing. You need the Kotlin serialization compiler plugin in Gradle for @Serializable to generate the converters at compile time (the same mechanism described in JSON Handling).

To see the idea behind negotiation without libraries, this runnable example chooses a representation from the Accept header, and keeps the decision in a plain function that is easy to test:

Kotlin Choosing a response format from the Accept header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the design: respond is a pure function from (path, accept) to (status, type, body), and the HTTP plumbing is a thin layer around it. The same split is the best habit in Ktor, where handlers should delegate to ordinary classes that know nothing about call.

Handling errors

Throwing exceptions from handlers is convenient, and the StatusPages plugin turns them into responses in one place:

Kotlin
install(StatusPages) {
    exception<IllegalArgumentException> { call, cause ->
        call.respond(HttpStatusCode.BadRequest, cause.message ?: "Bad request")
    }
    exception<NoSuchElementException> { call, _ ->
        call.respond(HttpStatusCode.NotFound)
    }
    status(HttpStatusCode.InternalServerError) { call, _ ->
        call.respondText("Something went wrong", status = HttpStatusCode.InternalServerError)
    }
}

With that in place, handlers can use require(...) and getValue(...) (see require, check and assert) and trust the plugin to map failures to 400 and 404. Never leak stack traces or internal messages to clients in production; send a short, safe text and log the details.

The Ktor client

The client is a separate artifact (ktor-client-core plus an engine such as CIO) with a suspending API. Create one HttpClient, reuse it, and close it when finished:

Kotlin
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val client = HttpClient(CIO) {
        install(ContentNegotiation) { json() }
    }

    val book: Book = client.get("http://localhost:8080/books/1").body()
    println(book.title)

    val created = client.post("http://localhost:8080/books") {
        contentType(ContentType.Application.Json)
        setBody(NewBook("Emma"))
    }
    println(created.status)      // 201 Created

    client.close()
}

get and post are suspend functions, so they must run in a coroutine (runBlocking in a small program, a scope in a real service). .body() converts the response to the type you ask for, using the client's own ContentNegotiation. Install timeouts (HttpTimeout) and retries for anything that calls another service: a network call without a timeout is a bug waiting for a bad day. Use one client for many requests; creating a client per request wastes connections.

Testing without a network

Ktor ships a test host that runs your module in memory: no port, no sockets, fast and deterministic.

Kotlin
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*

class BookRoutesTest {
    @Test
    fun returnsBook() = testApplication {
        application { module() }

        val response = client.get("/books/1")

        assertEquals(HttpStatusCode.OK, response.status)
        assertEquals("""{"id":1,"title":"Dune"}""", response.bodyAsText())
    }

    @Test
    fun unknownBookIs404() = testApplication {
        application { module() }
        assertEquals(HttpStatusCode.NotFound, client.get("/books/99").status)
    }
}

testApplication starts the module and gives you a client already pointed at it. This is why modules are written as extension functions of Application: tests can install exactly the module they need. See Testing Basics for the test framework itself.

Ktor and the rest of the ecosystem

  • Alternatives: Spring Boot is the most common JVM choice and works well with Kotlin (see the Advanced Java track). Http4k, Javalin and Micronaut also exist. Ktor stands out for being coroutine-first and light.
  • Multiplatform: the Ktor client runs on Android, iOS and the browser too (see Kotlin Multiplatform), which makes it a common choice for shared networking code.
  • Production concerns: configure logging, CORS, authentication (JWT or sessions), compression, and a connection pool for databases. Each is an installable plugin.
  • Deployment: the Ktor Gradle plugin builds a runnable fat JAR or a Docker image directly.

For the server-side picture, read Kotlin on the Server alongside this lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a Ktor 'module'?

    By convention a module is fun Application.module(). Several modules can be installed in one server, and tests can install only the one they need.
  2. 2. What does call.receive<NewBook>() do?

    receive reads the request body and deserializes it with the converter chosen by ContentNegotiation, based on the Content-Type header.
  3. 3. Which plugin turns thrown exceptions into HTTP responses?

    StatusPages lets you map exceptions or status codes to responses in one place, so handlers can stay short.
  4. 4. Why should you reuse one HttpClient?

    An HttpClient owns engine resources such as pooled connections. Create it once, reuse it, and call close() when the application ends.
  5. 5. What is the advantage of testApplication?

    testApplication runs the module in-process and provides a client wired to it, so tests are fast and deterministic.

Summary

  • Ktor builds HTTP servers and clients with Kotlin DSLs and suspending functions; the server is an engine, plugins, routing and handlers.
  • Configure the server in an Application.module() function, nest route, get and post blocks, and read inputs from call.parameters and call.receive<T>().
  • ContentNegotiation with kotlinx.serialization converts between Kotlin objects and JSON; StatusPages maps exceptions to status codes.
  • The HttpClient offers get, post and .body<T>(); reuse one client, add timeouts and close it at the end.
  • Keep logic in plain functions and classes, with handlers as a thin layer, and test with testApplication.
  • The runnable examples used the JDK's loopback HTTP server to show the same structure without external libraries.

Next: Calculator Project