Ktor provides the
Resources plugin that allows you to implement type-safe requests. To accomplish this, you need to create a class that describes resources available on a server and then annotate this class using the
@Resource keyword. Note that the
@Resource annotation has
@Serializable behavior provided by the kotlinx.serialization library.
Add Resources dependencies
Resources, you need to include the
ktor-client-resources artifact in the build script:
You can learn more about artifacts required by the Ktor client from Adding client dependencies.
Resources, pass it to the
install function inside a client configuration block:
Create resource classes
Each resource class should have the
@Resource annotation. Below, we'll take a look at several examples of resource classes - defining a single path segment, query and path parameters, and so on.
The example below shows how to define the
Articles class that specifies a resource responding on the
Resources with a query parameter
Articles class below has the
sort string property that acts as a query parameter and allows you to define a resource responding on the following path with the
sort query parameter:
Resources with nested classes
You can nest classes to create resources that contain several path segments. Note that in this case nested classes should have a property with an outer class type. The example below shows a resource responding on the
Resources with a path parameter
As an example, this resource can be used to respond on
Example: A resource for CRUD operations
Let's summarize the examples above and create the
Articles resource for CRUD operations.
This resource can be used to list all articles, post a new article, edit it, and so on. We'll see how to make type-safe requests to this resource in the next section.
Make type-safe requests
To make a request to a typed resource, you need to pass a resource class instance to a request function (
put, and so on). For example, the sample below shows how to make a request to the
The example below shows how to make typed requests to the
Articles resource created in Example: A resource for CRUD operations.
The defaultRequest function is used to specify a default URL for all requests.