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. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.
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. insiderouting { } - Path parameters:
{name}— access viacall.parameters["name"] - Query parameters:
call.request.queryParameters["key"] - Group routes with
route("/prefix") { }and extract to extension functions onRoute - Receive typed bodies with
call.receive(needs ContentNegotiation)()
Learn Kotlin with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Routing and Typed Parameters” lesson free?
Yes — any 3 lessons of the Kotlin Academy learning path, including “Routing and Typed Parameters”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.
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
- Ktor Project Setup: embeddedServer and Application Modules
- Routing and Typed Parameters
- Content Negotiation and kotlinx.serialization
- Authentication Plugins: JWT and Session