0Pricing
Kotlin Academy · Lesson

Routing and Typed Parameters

Define routes with path and query parameters and group them with route blocks.

Routing and Typed Parameters is a free Kotlin Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Ktor Routing Basics

Routing in Ktor is a plugin installed via install(Routing) { ... } or the shorthand routing { ... }. Routes are defined using HTTP-method functions: get, post, put, delete, patch.

routing {
    get("/hello") { call.respondText("Hello!") }
    post("/items") { /* handle POST */ }
}

Path Parameters

Define a path parameter with {name}. Access it via call.parameters["name"]. The value is always a String?:

get("/users/{id}") {
    val id = call.parameters["id"] ?: return@get call.respondText("Missing id", status = HttpStatusCode.BadRequest)
    call.respondText("User: $id")
}

Optional Path Segments

Mark a segment optional by adding ?: {name?}. If the segment is absent, call.parameters["name"] returns null.

get("/posts/{slug?}") {
    val slug = call.parameters["slug"]
    if (slug == null) call.respondText("All posts")
    else call.respondText("Post: $slug")
}

Typed Parameter Conversion

Convert path parameters to typed values using extension functions on Parameters. Ktor provides built-in helpers or you can write your own:

get("/items/{id}") {
    val id = call.parameters["id"]?.toLongOrNull()
        ?: return@get call.respond(HttpStatusCode.BadRequest, "Invalid id")
    call.respondText("Item #$id")
}

Query Parameters

Access query string parameters via call.request.queryParameters["key"]. Multiple values for the same key are available via getAll("key"):

get("/search") {
    val q = call.request.queryParameters["q"] ?: ""
    val page = call.request.queryParameters["page"]?.toIntOrNull() ?: 1
    call.respondText("Search: $q, page $page")
}

Route Grouping

Group related routes under a common prefix using route("/prefix") { ... }. This reduces repetition and makes the routing tree readable:

route("/api/v1") {
    route("/users") {
        get { /* list users */ }
        get("/{id}") { /* get user by id */ }
        post { /* create user */ }
    }
}

Organizing Routes in Functions

Extract route groups into extension functions on Route to keep the routing configuration modular:

fun Route.userRoutes() {
    route("/users") {
        get { /* ... */ }
        post { /* ... */ }
        get("/{id}") { /* ... */ }
    }
}

// In Application module:
routing { userRoutes() }

Handling Request Body

Receive a request body as text, bytes, or a deserialized object (requires ContentNegotiation plugin). Use call.receive() for typed deserialization:

post("/users") {
    val user = call.receive<UserDto>()
    call.respond(HttpStatusCode.Created, user)
}

Responding with Status Codes

Use call.respond(status, body) for full control, or the convenience methods call.respondText(), call.respondFile(), call.respond(HttpStatusCode.NotFound):

get("/users/{id}") {
    val user = userRepo.find(call.parameters["id"])
    if (user == null) call.respond(HttpStatusCode.NotFound)
    else call.respond(user)
}

Wildcard and Tailcard Routes

Use * for a single wildcard segment and {...} (tailcard) to match the rest of the path as a single parameter:

get("/static/{path...}") {
    val filePath = call.parameters.getAll("path")?.joinToString("/") ?: ""
    call.respondText("Serving: $filePath")
}

Route Priorities

Ktor evaluates routes in declaration order. More specific routes should be declared before wildcards. When two routes match, the first match wins.

Quick Check

How do you group multiple routes under a common URL prefix in Ktor?

Recap: Routing and Typed Parameters

Key takeaways:

  • Define routes with get, post, etc. inside routing { }
  • Path parameters: {name} — access via call.parameters["name"]
  • Query parameters: call.request.queryParameters["key"]
  • Group routes with route("/prefix") { } and extract to extension functions on Route
  • Receive typed bodies with call.receive() (needs ContentNegotiation)

Frequently asked questions

Is the “Routing and Typed Parameters” lesson free?

Yes — the full text of “Routing and Typed Parameters” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “Routing and Typed Parameters”?

Define routes with path and query parameters and group them with route blocks. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Routing and Typed Parameters” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Ktor Project Setup: embeddedServer and Application Modules
  2. Routing and Typed Parameters
  3. Content Negotiation and kotlinx.serialization
  4. Authentication Plugins: JWT and Session
← Back to Kotlin Academy