Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Your First Ktor Server

Write and run your first Ktor server: embeddedServer, routing, call.respondText, and a runnable JDK HTTP server stand-in that you can call from the same program.

Time to write a server. In this lesson you will write the classic first Ktor server, understand each line, add a few more routes, and then run a real HTTP server in the in-browser runner that behaves the way a Ktor server does: it listens on a port, handles a request and answers a client in the same program.

The embeddedServer style

embeddedServer creates and starts the server from your own main(). This is the style used in most small examples and in tests:

Kotlin
import io.ktor.http.*
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, host = "0.0.0.0", module = Application::module)
        .start(wait = true)
}

fun Application.module() {
    routing {
        get("/") {
            call.respondText("Hello, world!")
        }
        get("/html") {
            call.respondText(
                "<h1>Hello from Ktor</h1>",
                ContentType.Text.Html
            )
        }
        get("/status") {
            call.respondText("Created!", status = HttpStatusCode.Created)
        }
    }
}
  • host = "0.0.0.0" makes the server reachable from other machines (and from inside a Docker container). The default 0.0.0.0 is used by the engine; 127.0.0.1 would restrict it to your own computer.
  • module = Application::module passes the function that configures the app, so main() stays tiny and the same module() is reused by tests.
  • start(wait = true) blocks. With wait = false it returns immediately, which is what tests want.

Run it with ./gradlew run, then open http://localhost:8080/. You will see log lines such as Responding at http://0.0.0.0:8080.

Everything in call

Inside a handler, call is an ApplicationCall. It bundles:

Member Purpose
call.request The incoming request: method, URI, headers, parameters, body
call.response The outgoing response: status, headers, cookies
call.parameters Path and query parameters
call.respondText, call.respond Send a response
call.receive<T>() Read and convert the request body
call.application The Application instance

A handler must send exactly one response. If you never respond, the client waits until it times out; if you respond twice, Ktor throws ResponseAlreadySentException. Most handlers end with a single call.respond... call.

Stand-in: a real HTTP server in one program

The JDK ships a small HTTP server (com.sun.net.httpserver). It is not Ktor, but it speaks real HTTP over a real socket, so it is a good stand-in. We bind to port 0 (the OS picks a free port) on the loopback address, handle requests, call them with java.net.http.HttpClient, and shut down.

Kotlin Stand-in: a real HTTP server on loopback

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.

Look at the mapping:

JDK stand-in Ktor
server.createContext("/status") { call -> ... } get("/status") { ... }
call.respondText("Created!", status = 201) call.respondText("Created!", status = HttpStatusCode.Created)
HttpClient.send(...) Ktor HttpClient or testApplication { client.get(...) }

Notice /nothing: the JDK server's root context catches everything, so it replies 200 for any path. Ktor's router is stricter: an unmatched path gives 404 Not Found. The routing basics lesson builds that behaviour.

The EngineMain style

The other way to start a Ktor server is to let Ktor read a configuration file and call your module. You set mainClass to io.ktor.server.netty.EngineMain in Gradle, and your code contains no main() at all:

Kotlin
// src/main/kotlin/Application.kt
fun Application.module() {
    routing {
        get("/") { call.respondText("Hello from EngineMain") }
    }
}
TEXT
# src/main/resources/application.conf
ktor {
    deployment {
        port = 8080
    }
    application {
        modules = [ com.example.ApplicationKt.module ]
    }
}

This is the style the project generator creates, and the style you would use for production because the port and modules can be changed without recompiling. The next lesson goes into configuration in detail.

Common first-run problems

  • "Address already in use": something else uses port 8080. Change the port or stop the other process.
  • A blank page and no logs: you forgot wait = true (so main() exited) or you have no logging dependency.
  • 404 for a route you wrote: check the exact path and method; get("/hello") does not answer POST /hello.
  • Unresolved reference: respondText: a missing import. Ktor splits extension functions across packages (io.ktor.server.response.*, io.ktor.server.routing.*), and IntelliJ's import quick-fix finds them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does start(wait = true) do?

    wait = true keeps main() alive. With wait = false it returns, which suits tests.
  2. 2. What happens if a handler never calls a call.respond... function?

    A handler is responsible for answering; no response means a hanging request.
  3. 3. Why pass module = Application::module to embeddedServer?

    Keeping configuration in a module function lets main() and test code share it.
  4. 4. In the stand-in, why bind to port 0?

    Binding to 0 asks the OS for a free port; the program reads it from server.address.port.

Summary

  • embeddedServer(Netty, port = ...) { ... } builds a server from main(); EngineMain builds it from application.conf.
  • Handlers use call to read the request and send exactly one response.
  • call.respondText takes a content type and a status code.
  • The JDK HttpServer stand-in shows a real server and a real client talking over loopback.
  • Common problems: port conflicts, missing wait = true, wrong method or path, missing imports.

Next: Application Modules and Configuration