Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 38 ยท Routing and Requests

Requests and Responses

Work with Ktor's ApplicationRequest and ApplicationResponse: read headers, text, form and JSON bodies with receive, and send text, HTML, files and objects with respond.

Every handler is a conversation: read what the client sent, decide, and answer once. This lesson covers the two halves of that conversation. On the request side: method, URI, headers, cookies and the body (call.receive). On the response side: the many forms of call.respond, and how Ktor decides the content type of what you send.

The request

call.request is an ApplicationRequest:

Kotlin
post("/inspect") {
    val request = call.request
    val method = request.httpMethod.value            // "POST"
    val uri = request.uri                            // "/inspect?x=1"
    val path = request.path()                        // "/inspect"
    val agent = request.headers["User-Agent"]        // String?
    val type = request.contentType()                 // ContentType (e.g. application/json)
    val length = request.contentLength()             // Long?
    val cookie = request.cookies["theme"]            // String?
    val host = request.origin.remoteHost             // client address (after proxy rules)
    call.respondText("$method $path from $host")
}

Header names are case-insensitive: headers["content-type"] and headers["Content-Type"] are the same.

Receiving the body

call.receive<T>() reads the body and converts it to T. What is supported depends on T and on the installed plugins:

Kotlin
post("/text") {
    val text = call.receiveText()                    // the whole body as a String
    call.respondText("You sent ${text.length} characters")
}

post("/form") {
    val form = call.receiveParameters()              // application/x-www-form-urlencoded
    val name = form["name"] ?: return@post call.respond(HttpStatusCode.BadRequest, "name required")
    call.respondText("Hello, $name")
}

post("/bytes") {
    val bytes = call.receive<ByteArray>()
    call.respondText("${bytes.size} bytes")
}

post("/json") {
    val book = call.receive<Book>()                  // needs ContentNegotiation + kotlinx.serialization
    call.respond(HttpStatusCode.Created, book)
}

Important details:

  • The body can be read once. Calling receive twice for the same call fails unless you install the DoubleReceive plugin.
  • For multipart uploads use call.receiveMultipart(), which streams the parts.
  • If the client sends a body the server cannot convert (bad JSON, wrong content type), receive throws BadRequestException or UnsupportedMediaTypeException. The Status pages lesson turns those into clean responses.
  • There is no request size limit by default on receiveText; a malicious client could send gigabytes. Use the RequestBodyLimit-style checks (or check contentLength()) for public endpoints.

Responding

call.respond is the general form. It takes a status code and a message object, which can be a string, byte array, a file, a stream, or any object your installed plugins can serialize:

Kotlin
get("/examples") {
    call.respondText("plain")                                  // 200 text/plain
    // Only ONE response per call; the rest are alternatives:
    call.respondText("<h1>Hi</h1>", ContentType.Text.Html)
    call.respond(HttpStatusCode.Accepted)                      // status only
    call.respond(HttpStatusCode.Created, Book(1, "Kotlin"))    // JSON via ContentNegotiation
    call.respondBytes(byteArrayOf(1, 2, 3), ContentType.Application.OctetStream)
    call.respondFile(File("report.pdf"))
    call.respondRedirect("/new-location", permanent = false)   // 302
}

Choose exactly one. The headline functions:

Function Sends
respondText(text, contentType, status) A string
respond(status) Only a status line
respond(message) An object, converted by ContentNegotiation
respondBytes Raw bytes
respondFile A file with content type from its extension
respondRedirect(url) A 302 (or 301 if permanent = true)
respondOutputStream / respondTextWriter Streaming output

Setting headers and cookies goes through call.response, and must happen before you respond, because headers are sent with the first bytes:

Kotlin
get("/with-headers") {
    call.response.headers.append("X-Request-Source", "ktor-course")
    call.response.cookies.append("theme", "dark", maxAge = 3600, path = "/")
    call.respondText("ok")
}

Stand-in: a real round trip with headers, forms and bodies

This stand-in uses the JDK HTTP server (a real server over loopback) and shows the same request/response mechanics: reading headers and bodies, parsing a form body, and answering with a header and a status.

Kotlin Stand-in: reading requests, writing responses

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.

Observe: the body was read once; headers were added before sending; the missing field produced a 400, and a successful creation a 201.

receive and content types

receive<T>() looks at the request's Content-Type and picks a converter registered by ContentNegotiation (JSON, XML, CBOR...). If the client says Content-Type: application/json but the plugin is not installed, you get UnsupportedMediaTypeException (HTTP 415). This is why the Content Negotiation lesson matters right after this one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function reads a form posted as application/x-www-form-urlencoded?

    receiveParameters parses an urlencoded form body into Parameters.
  2. 2. When must response headers be set?

    Headers go out with the first bytes, so add them before responding.
  3. 3. What happens if you call call.receive<T>() twice for one request without extra plugins?

    The body stream is read once; use the DoubleReceive plugin if you truly need it twice.
  4. 4. Which response function sends a 302 redirect by default?

    respondRedirect(url) sends 302; permanent = true sends 301.

Summary

  • call.request exposes method, URI, headers, cookies and the body; call.response sets headers and cookies.
  • receiveText, receiveParameters, receive<T>() and receiveMultipart read the body once.
  • Respond exactly once with respondText, respond, respondBytes, respondFile or respondRedirect.
  • Set headers before responding; treat unconvertible bodies as client errors.

Next: Status Codes and Headers