Routing
- Kotlin course
- Advanced
- Lesson 20/83
- 5 min
Learn URL routes with routing.
What is routing?
Routing directs incoming HTTP requests to handler functions by URL path. In Ktor it is declared with the routing block.
Example: routing { get("/users") { call.respondText("users") } }. Here a GET request to /users is answered with call.respondText. Each route binds to an HTTP method: get, post, put, delete. Path parameters use the {id} syntax. The routing block lives inside the Application module.
HTTP methods
In the routing block each route binds to an HTTP method. get reads, post creates, put updates and delete removes.
Example: post("/users") { call.respondText("Created") }. To return a response use call.respondText, call.respond or call.respondBytes. To read the request body use call.receive<T>(). Path parameters are read with call.parameters["id"]. Routing is the basis of REST API design.
Practice Add a route with routing
Define fun Application.module(). Inside it, open a routing { get("/users") { } } block. Also print println("Route added") inside fun main().
Starter code
// Routing
// write here
import io.ktor.server.application.*
import io.ktor.server.routing.*
fun main() {
}Sample solution
fun Application.module() {
routing {
get("/users") {
}
}
}
fun main() {
println("Route added")
}Expected output
Route added
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the routing block
fun Application.module() {
____ {
get("/users") { }
}
}
fun Application.module() {
routing {
get("/users") { }
}
}
Explanation: The routing block holds the route definitions.
2 Match HTTP methods
| Term | Meaning |
|---|---|
get |
Read |
post |
Create |
put |
Update |
delete |
Delete |
3 Which is used to read a path parameter?
- call.respond
- call.respondText
- call.receive
- call.parameters Correct answer
Explanation: call.parameters reads a path parameter.