Locations
Ktor provides a mechanism to create routes in a typed way, for both: constructing URLs and reading the parameters.
Add dependencies
To enable Locations
support, you need to include the ktor-locations
artifact in the build script:
Install Locations
To install the Locations
plugin, pass it to the install
function in the application initialization code. Depending on the way used to create a server, this can be the embeddedServer
function call ...
... or a specified module.
Define route classes
For each typed route you want to handle, you need to create a class (usually a data class) containing the parameters that you want to handle.
The parameters must be of any type supported by the Data Conversion plugin. By default, you can use Int
, Long
, Float
, Double
, Boolean
, String
, enums and Iterable
as parameters.
URL parameters
That class must be annotated with @Location
specifying a path to match with placeholders between curly brackets {
and }
. For example: {propertyName}
. The names between the curly braces must match the properties of the class.
Will match:
/list/movies/page/10
Will construct:
Listing(name = "movies", page = 10)
GET parameters
If you provide additional class properties that are not part of the path of the @Location
, those parameters will be obtained from the GET's query string or POST parameters:
Will match:
/list/movies?page=10&count=20
Will construct:
Listing(name = "movies", page = 10, count = 20)
Define route handlers
Once you have defined the classes annotated with @Location
, this plugin artifact exposes new typed methods for defining route handlers: get
, options
, header
, post
, put
, delete
and patch
.
Build URLs
You can construct URLs to your routes by calling application.locations.href
with an instance of a class annotated with @Location
:
So for this class, path
would be "/list/movies?page=10&count=20""
.
If you construct the URLs like this, and you decide to change the format of the URL, you will just have to update the @Location
path, which is really convenient.
Subroutes with parameters
You have to create classes referencing to another class annotated with @Location
like this, and register them normally:
To obtain parameters defined in the superior locations, you just have to include those property names in your classes for the internal routes. For example: