Organizing routes in Ktor
In Ktor, structuring multiple routes belonging to the same domain can be streamlined for better organization and readability. Our current routing{}
block includes various endpoints, some of which are related to cats.
Here’s how our routing
block looks currently:
routing {
get("/status") {
...
}
post("/cats") {
...
}
get("/cats") {
...
}
get("/cats/{id}") {
...
}
}
To improve the structure, we can extract all cat-related routes into a separate function:
fun Routing.catsRoutes() {
...
}
In IntelliJ IDEA, there’s even an option to automatically generate an extension function on the Routing
class.
To tidy this up, we replace the cat-related routes with a dedicated function:
routing {
get("/status") {
...
}
catsRoutes()
}
We can now consolidate all our cat-related routes into...