https://kotlinlang.org logo
#ktor
Title
# ktor
s

Sourabh Rawat

10/04/2021, 1:57 PM
Hi, in Ktor-client, how do I set path parameter if I have a url template like
<https://foo.com/{id}/car/{bar}>
? I need to set the values of
id
and
bar
Thanks in advance.
m

Matteo Mirk

10/04/2021, 2:17 PM
I don’t think ktor-client has a built-in facility, but you could just use string templates:
Copy code
fun urlTemplate(id: String, bar: String) = "<https://foo.com/${id}/car/${bar}>"

urlTemplate("1", "foo") // <https://foo.com/1/car/foo>
c

christophsturm

10/04/2021, 2:29 PM
you need to be really careful with string templates because they are not really type safe. if you change the type of id or bar to something else kotlin will automatically call toString
👍 1
which is not a problem when you encapsulate it in a type safe method like in this example. (or have good code coverage)
s

Sourabh Rawat

10/05/2021, 7:14 AM
The issue is that we store endpoints in application.yaml so I am not sure how can I use
urlTemplate
for that.
c

christophsturm

10/05/2021, 8:19 AM
how do you add the parameters to them currently?
m

Matteo Mirk

10/05/2021, 10:01 AM
Instead of a yaml file, store them in a kotlin file, each one in its own function: that way you can call them lazily in your client code. The advantage is that this kind of configuration is still code, checked by the compiler, instead of a semi-structured text file with all the problems that YAML brings along 😉
👍 1
Hey @Sourabh Rawat, inspired by your problem I wrote this, maybe it could be useful: https://kotlinlang.slack.com/archives/C0BJ0GTE2/p1634286003392100
💯 1
4 Views