Chuyển đến nội dung

Bài 10 · Routing and Requests

Structured Routing and Resources

Organize a growing Ktor API: nested route blocks, extension functions per feature, the Resources plugin for type-safe routes, and serving static files.

A tutorial with three routes fits in one block. A real API has dozens, and putting them all in one routing { } becomes hard to read. Ktor gives you three tools to stay organised: nested route { } blocks to share a path prefix, extension functions on Route to move each feature to its own file, and the Resources plugin for type-safe URLs. This lesson shows all three, plus static files, with a runnable stand-in for the route tree.

Nesting with route

route("/books") { ... } creates a group. Everything inside has the prefix, and the inner paths are relative:

Kotlin
routing {
    route("/books") {
        get {                                   // GET /books
            call.respond(repository.all())
        }
        post {                                  // POST /books
            call.respond(HttpStatusCode.Created, repository.add(call.receive<NewBook>()))
        }
        route("/{id}") {
            get {                               // GET /books/{id}
                val book = repository.find(call.parameters.getOrFail<Int>("id"))
                    ?: return@get call.respond(HttpStatusCode.NotFound)
                call.respond(book)
            }
            delete {                            // DELETE /books/{id}
                repository.remove(call.parameters.getOrFail<Int>("id"))
                call.respond(HttpStatusCode.NoContent)
            }
        }
    }
}

Notice get { } without a path: it handles the group's own path. Nesting means each URL fragment appears once, so changing /books to /library/books is a one-line edit. You can also nest by method with route("/x", HttpMethod.Get) { }, and use route to attach plugins to a subtree, which the plugins chapter and the authentication chapter exploit (authenticate("name") { ... } is exactly such a group).

One extension function per feature

The idiom for real projects is an extension function on Route, one per resource, each in its own file:

Kotlin
// BookRoutes.kt
fun Route.bookRoutes(repository: BookRepository) {
    route("/books") {
        get { call.respond(repository.all()) }
        get("/{id}") { /* ... */ }
        post { /* ... */ }
    }
}

// UserRoutes.kt
fun Route.userRoutes() {
    route("/users") { /* ... */ }
}

// Routing.kt
fun Application.configureRouting(repository: BookRepository) {
    routing {
        bookRoutes(repository)
        userRoutes()
        get("/health") { call.respondText("ok") }
    }
}

Dependencies, such as the repository, are passed as ordinary arguments. That keeps handlers easy to test and avoids a DI framework until you truly need one (Koin is the common choice when you do).

Type-safe routing with Resources

String paths are easy to mistype and cannot be checked by the compiler. The Resources plugin (ktor-server-resources, plus kotlin("plugin.serialization")) lets you describe URLs as classes:

Kotlin
import io.ktor.resources.*
import io.ktor.server.resources.*

@Resource("/articles")
class Articles(val sort: String? = "new") {
    @Resource("new")
    class New(val parent: Articles = Articles())

    @Resource("{id}")
    class Id(val parent: Articles = Articles(), val id: Long) {
        @Resource("edit")
        class Edit(val parent: Id)
    }
}

fun Application.module() {
    install(Resources)
    routing {
        get<Articles> { articles ->                       // GET /articles?sort=new
            call.respondText("Articles sorted by ${articles.sort}")
        }
        get<Articles.Id> { article ->                     // GET /articles/{id}
            call.respondText("Article ${article.id}")
        }
    }
}

A class property becomes a query parameter (sort), a in the path becomes a path parameter bound to the property of the same name (and converted to Long, with a 400 if it is not a number), and parent expresses nesting. The handler receives the typed object. You can also build URLs from the same classes with href(Articles.Id(id = 5)), so a link can never point to a route that does not exist.

Stand-in: a route tree you can print

The next program builds a nested route tree with the same route { } idiom, and flattens it so you can see the final URLs. It also shows how a type-safe resource class can render itself to a URL, by writing a small href function. It is a stand-in; real Ktor does the matching for you, but this is the data structure behind it.

Kotlin Stand-in: nested routes flatten to full paths

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.

The route("/{id}") { ... } block appears once, yet both GET and DELETE get the full /books/{id} URL, and the typed href() can only produce URLs that exist.

Static content

Serve files and a single-page application from the routing block:

Kotlin
routing {
    staticResources("/static", "assets")   // /static/app.css -> src/main/resources/assets/app.css
    staticFiles("/downloads", File("files"))   // files from a directory on disk
    singlePageApplication {                // index.html fallback for client-side routes
        react("frontend/dist")
    }
}

staticResources serves files packaged inside your JAR; staticFiles reads a directory at runtime. Both set content types, support conditional requests and guard against ../ path traversal.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does get { ... } (no path) mean inside route("/books") { ... }?

    A method function without a path attaches to the enclosing route's path.
  2. 2. Why declare route groups as fun Route.bookRoutes() in separate files?

    Extension functions on Route are a convention for organising routes by feature.
  3. 3. With the Resources plugin, how does the sort property of class Articles(val sort: String?) get its value?

    Properties not mentioned in the path template become query parameters.
  4. 4. Which function serves files bundled inside the application JAR?

    staticResources reads from the classpath; staticFiles reads from the file system.

Summary

  • Nest route("/prefix") { ... } to share path fragments and attach plugins to a subtree.
  • Put each feature in fun Route.featureRoutes() and pass dependencies as parameters.
  • The Resources plugin turns URLs into typed classes with compiler-checked parameters and href.
  • Use staticResources, staticFiles and singlePageApplication for static content.

Chapter 3 moves from routes to the features around them: plugins.

Next: Plugins and Interceptors

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.