Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Routing and Requests

Routing Basics

Learn Ktor routing: get, post, put and delete handlers, path templates, wildcards, tail segments, and how a router chooses between competing routes.

Routing decides which code answers a request. You declare a tree of paths and HTTP methods inside the routing { } block, and Ktor picks the best match for every incoming call. This lesson covers the building blocks (method functions and path templates), the matching rules that decide which route wins, and a runnable stand-in router that implements those rules so you can experiment.

Method functions

Inside routing { } you use one function per HTTP method:

Kotlin
routing {
    get("/books") { call.respondText("list of books") }
    post("/books") { call.respondText("create a book") }
    put("/books/42") { call.respondText("replace book 42") }
    patch("/books/42") { call.respondText("update part of book 42") }
    delete("/books/42") { call.respondText("delete book 42") }
    head("/books") { call.respond(HttpStatusCode.OK) }
    options("/books") { call.respond(HttpStatusCode.NoContent) }
}

The same path can have a different handler per method. A request whose method has no handler (for example PUT /books) is not a 404 in HTTP terms but a 405 Method Not Allowed; in Ktor you get 404 unless you add a handler or a plugin that reports 405. We deal with that in the status codes lesson.

Prefer the semantics from REST: GET reads and never changes data, POST creates, PUT replaces, PATCH changes part of a resource, DELETE removes. See the HTTP and REST ideas in REST APIs if these are new.

Path templates

A path can contain segments that are fixed or variable:

Pattern Matches Does not match
/books /books /books/1, /book
/books/{id} /books/42, /books/abc /books, /books/42/pages
/books/{id?} /books and /books/42 /books/42/pages
/files/{path...} /files/a, /files/a/b/c.txt /other
/users/*/photos /users/ann/photos, /users/bob/photos /users/photos
  • captures one segment into a parameter. Read it with call.parameters["name"].
  • {name?} makes the segment optional.
  • {name...} is a tail: it captures every remaining segment, as a list. Useful for static files and proxies.
  • * matches any one segment but does not capture it.
Kotlin
get("/books/{id}") {
    val id = call.parameters["id"]
    call.respondText("Book $id")
}
get("/files/{path...}") {
    val parts = call.parameters.getAll("path").orEmpty()
    call.respondText("File parts: $parts")
}

Which route wins?

Several routes can match the same URL. Ktor gives each route a quality score by how specific it is and picks the highest. In practice the rules are:

  1. A constant segment beats a parameter segment (/books/new beats /books/{id}).
  2. A parameter beats a wildcard, and a wildcard beats a tail.
  3. A route that matches the method beats one that does not.
  4. If two routes are equally specific, the one declared first wins, so order matters only for ties.

This is why you can safely write both get("/users/me") and get("/users/{id}"): a request for /users/me goes to the constant route regardless of declaration order.

Stand-in: a router that picks the most specific route

The program below implements those rules in plain Kotlin: segments are compiled to constant, parameter, optional, wildcard and tail matchers, each with a specificity score, and the router chooses the best-scoring route. Run it and try adding your own routes.

Kotlin Stand-in: path templates and specificity

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 /books/new resolves to the constant route even though /books/{id} was declared first, and /files/a/b/c.txt captures three segments as a list.

Routes are nested lazily and cheap

routing { } is evaluated once at startup. Ktor builds the tree then; at request time it only walks the tree. So you can declare thousands of routes without slowing requests, and you must not put request-dependent logic outside the handler lambda: code in the routing block itself runs once, not per request.

Kotlin
routing {
    val startedAt = System.currentTimeMillis()   // runs ONCE at startup
    get("/uptime") {
        val now = System.currentTimeMillis()      // runs on EVERY request
        call.respondText("up for ${now - startedAt} ms")
    }
}

Trailing slashes

By default /books and /books/ are the same route for matching. Ktor also has an IgnoreTrailingSlash plugin for redirect-free matching across both forms; install it if clients are inconsistent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Both get("/users/me") and get("/users/{id}") exist. Which handles /users/me?

    Constants beat parameters, regardless of declaration order.
  2. 2. What does {path...} capture?

    A tail captures the rest of the path; read it with call.parameters.getAll("path").
  3. 3. When does the code placed directly inside routing { } (outside handlers) run?

    The routing block builds the tree once; only handler lambdas run per request.
  4. 4. Which pattern matches both /books and /books/42?

    {id?} makes the segment optional. The tail pattern would also match, but captures a list.

Summary

  • Use get, post, put, patch, delete and friends inside routing { }.
  • Templates: one segment, {id?} optional, {path...} tail, * wildcard.
  • Specificity decides: constant, then parameter, then wildcard, then tail; ties go to the first declared.
  • The routing block runs once at startup; handlers run per request.

Next: Path and Query Parameters