Back to list

Ktor-style Routing DSL

Lv.51042@mukitaro0 playsJan 2, 2026

Ktor routing DSL pattern. JetBrains' async web framework for Kotlin.

preview.kotlin
Kotlin
1import io.ktor.server.application.*
2import io.ktor.server.response.*
3import io.ktor.server.routing.*
4import io.ktor.server.request.*
5
6data class User(val id: Int, val name: String, val email: String)
7
8fun Application.configureRouting() {
9 routing {
10 route("/api") {
11 get("/users") {
12 val users = listOf(
13 User(1, "Alice", "alice@example.com"),
14 User(2, "Bob", "bob@example.com")
15 )
16 call.respond(users)
17 }
18
19 get("/users/{id}") {
20 val id = call.parameters["id"]?.toIntOrNull()
21 if (id == null) {
22 call.respondText("Invalid ID", status = HttpStatusCode.BadRequest)
23 return@get
24 }
25 call.respond(User(id, "User$id", "user$id@example.com"))
26 }
27
28 post("/users") {
29 val user = call.receive<User>()
30 call.respond(HttpStatusCode.Created, user)
31 }
32 }
33 }
34}

Custom problems are not included in rankings