Structured Handling of HTTP Requests

Routing is a feature that is installed into an Application to simplify and structure page request handling.

This page explains the routing feature. Extracting information about a request,and generating valid responses inside a route, is described on the requests and responses pages.

  1. application.install(Routing) {
  2. get("/") {
  3. call.respondText("Hello, World!")
  4. }
  5. get("/bye") {
  6. call.respondText("Good bye, World!")
  7. }
  8. }

get, post, put, delete, head and options functions are convenience shortcuts to a flexible and powerful routing system. In particular, get is an alias to route(HttpMethod.Get, path) { handle(body) }, where body is a lambda passed to theget function.

This feature is defined in the class io.ktor.routing.Routing and no additional artifacts are required.

Routing Tree

Routing is organized in a tree with a recursive matching system that is capable of handling quite complex rulesfor request processing. The Tree is built with nodes and selectors. The Node contains handlers and interceptors, and the selector is attached to an arc which connects another node. If selector matches current routing evaluation context, the algorithm goes down to the node associated with that selector.

Routing is built using a DSL in a nested manner:

  1. route("a") { // matches first segment with the value "a"
  2. route("b") { // matches second segment with the value "b"
  3. get {…} // matches GET verb, and installs a handler
  4. post {…} // matches POST verb, and installs a handler
  5. }
  6. }
  1. method(HttpMethod.Get) { // matches GET verb
  2. route("a") { // matches first segment with the value "a"
  3. route("b") { // matches second segment with the value "b"
  4. handle { } // installs handler
  5. }
  6. }
  7. }

Route resolution algorithms go through nodes recursively discarding subtrees where selector didn’t match.

Builder functions:

  • route(path) – adds path segments matcher(s), see below about paths
  • method(verb) – adds HTTP method matcher.
  • param(name, value) – adds matcher for a specific value of the query parameter
  • param(name) – adds matcher that checks for the existence of a query parameter and captures its value
  • optionalParam(name) – adds matcher that captures the value of a query parameter if it exists
  • header(name, value) – adds matcher that for a specific value of HTTP header, see below about quality

Path

Building routing tree by hand would be very inconvenient. Thus there is route function that covers most of the use cases in a simple way, using path.

route function (and respective HTTP verb aliases) receives a path as a parameter which is processed to build routingtree. First, it is split into path segments by the '/' delimiter. Each segment generates a nested routing node.

These two variants are equivalent:

  1. route("/foo/bar") { } // (1)
  2. route("/foo") {
  3. route("bar") { } // (2)
  4. }

Parameters

Path can also contain parameters that match specific path segment and capture its value into parameters propertiesof an application call:

  1. get("/user/{login}") {
  2. val login = call.parameters["login"]
  3. }

When user agent requests /user/john using GET method, this route is matched and parameters propertywill have "login" key with value "john".

Optional, Wildcard, Tailcard

Parameters and path segments can be optional or capture entire remainder of URI.

  • {param?} – optional path segment, if it exists it’s captured in the parameter
  • * – wildcard, any segment will match, but shouldn’t be missing
  • {…}– tailcard, matches all the rest of the URI, should be last. Can be empty.
  • {param…} – captured tailcard, matches all the rest of the URI and puts multiple values for each path segment into parameters using param as key. Use call.parameters.getAll("param") to get all values.

Examples:

  1. get("/user/{login}/{fullname?}") { }
  2. get("/resources/{path...}") { }

Quality

It is not unlikely that several routes can match to the same HTTP request.

One example is matching on the Accept HTTP header which can have multiple values with specified priority (quality).

  1. accept(ContentType.Text.Plain) { }
  2. accept(ContentType.Text.Html) { }

The routing matching algorithm not only checks if a particular HTTP request matches a specific path in a routing tree, butit also calculates the quality of the match and selects the routing node with the best quality. Given the routes above,which match on the Accept header, and given the request header Accept: text/plain; q=0.5, text/html will matchtext/html because the quality factor in the HTTP header indicates a lower quality fortext/plain (default is 1.0).

The Header Accept: text/plain, text/* will match text/plain. Wildcard matches are considered less specific than direct matches. Therefore the routing matching algorithm will consider them to have a lower quality.

Another example is making short URLs to named entities, e.g. users, and still being able to prefer specific pages like “settings”. An example would be

This can be implemented like this:

  1. get("/{user}") { }
  2. get("/settings") { }

The parameter is considered to have a lower quality than a constant string, so that even if /settings matches both,the second route will be selected.

Interception

When routing node is selected, the routing system builds a special pipeline to execute the node.This pipeline consists of handler(s) for the selected node and any interceptors installed into nodes thatconstitutes path from root to the selected node in order from top to bottom.

  1. route("/portal") {
  2. route("articles") { }
  3. route("admin") {
  4. intercept(ApplicationCallPipeline.Features) { } // verify admin privileges
  5. route("article/{id}") { } // manage article with {id}
  6. route("profile/{id}") { } // manage profile with {id}
  7. }
  8. }

Given the routing tree above, when request URI starts with /portal/articles, routing will handle call normally, but if the request is in /portal/admin section, it will first execute interceptor to validateif the current user has enough privilege to access admin pages.

Other examples could be installing JSON serialisation into /api section, loading user from the database in /user/{id} section and placing it into call’s attributes, etc.

Extensibility

The ktor-server-core module contains a number of basic selectors to match method, path, headers and query parameters, butyou can easily add your own selectors to fit in even more complex logic. Implement RouteSelector and createa builder function similar to built-in.

Path parsing is not extensible.

Tracing the routing decisions

If you have problems trying to figure out why your route is not being executed,Ktor provides a trace method inside the routing feature.

  1. routing {
  2. trace { application.log.trace(it.buildText()) }
  3. }

This method is executed whenever a call is done giving you a trace of the decisionstaken. As an example, for this routing configuration:

  1. routing {
  2. trace { application.log.trace(it.buildText()) }
  3. get("/bar") { call.respond("/bar") }
  4. get("/baz") { call.respond("/baz") }
  5. get("/baz/x") { call.respond("/baz/x") }
  6. get("/baz/x/{optional?}") { call.respond("/baz/x/{optional?}") }
  7. get("/baz/{y}") { call.respond("/baz/{y}") }
  8. get("/baz/{y}/value") { call.respond("/baz/{y}/value") }
  9. get("/{param}") { call.respond("/{param}") }
  10. get("/{param}/x") { call.respond("/{param}/x") }
  11. get("/{param}/x/z") { call.respond("/{param}/x/z") }
  12. get("/*/extra") { call.respond("/*/extra") }
  13. }

The output if requesting /bar would be:

  1. Trace for [bar]
  2. /, segment:0 -> SUCCESS @ /bar/(method:GET))
  3. /bar, segment:1 -> SUCCESS @ /bar/(method:GET))
  4. /bar/(method:GET), segment:1 -> SUCCESS @ /bar/(method:GET))
  5. /baz, segment:0 -> FAILURE "Selector didn't match" @ /baz)
  6. /{param}, segment:0 -> FAILURE "Better match was already found" @ /{param})
  7. /*, segment:0 -> FAILURE "Better match was already found" @ /*)

Remember to remove or disable this function when going into production.