Routing in Ktor

    This is accomplished using the Routing Feature which can be installed in any Ktor server application:

    route takes three parameters:

    • The URL pattern

    • The Verb, which can be GET, POST, PUT, DELETE, HEAD, OPTION, or PATCH

    • The Handler, which provides us with access to handling the request

    1. routing {
    2. route("/hello", HttpMethod.Get) {
    3. handle {
    4. call.respondText("Hello")
    5. }
    6. }

    We can see that we’ve replaced with the routing function.

    Similar to how routing simplifies usage of the Routing Feature, Ktor provides a series of functions that make defining route handlers much easier and more concise. The previous code can be expressed as:

    We can see that the route function is replaced with a get function that now only needs to take the URL and the code to handle the request. In a similar way Ktor provides functions for all the other verbs, that is put, post, head, and so on.

    If we want to define multiple route handlers, which of course is the case for any application, we can just add them to the routing function:

    1. routing {
    2. get("/customer/{id}") {
    3. }
    4. post("/customer") {
    5. }
    6. get("/order/{id}") {
    7. }

    In this case, each route has its own function and responds to the specific endpoint and HTTP verb.

    Independently of how we do the grouping, Ktor also allows us to have sub-routes as parameters to route functions. The following example shows us how to respond to incoming requests to /order/shipment:

    1. routing {
    2. route("/order") {
    3. route("/shipment") {
    4. get {
    5. }
    6. post {
    7. }
    8. }
    9. }

    A common pattern is to use extension functions on the Route type to define the actual routes, allowing us easy access to the verbs and remove clutter of having all routes in a single routing function. We can apply this pattern independently of how we decide to group routes. As such, the first example could be represented in a cleaner way:

    For our application to scale when it comes to maintainability, it is recommended to follow certain .