https://kotlinlang.org logo
Title
a

Andre Stefanov

08/21/2021, 11:49 PM
hello everyone! i am building a ktor backend at the moment and use Locations for the routing. the documentation states
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
While this seems to work fine for non-optional query parameters, i can't find any documentation on how to make the query parameters optional. out of intuition i tried to make location data class parameters nullable but this does not seem to lead to expected behavior. I wanted to have these routes:
/user?page=1&count=10
/user/{id}
this was done with following code:
@Location("/user")
data class UserRoute(val page: Int?, val count: Int?) {

    @Location("/{id}")
    data class ById(val parent: UserRoute, val id: String)

}
but now performing a GET on
/user
results in a 404 if i don't provide the query parameters and works perfectly for
/user?page=1&count=10
is there any documentation i missed or maybe someone can give me a quick kick into the right direction? thank you in advance!
😄 1
oh man ... i simply love rubberduck debugging. 10 seconds after posting this question i came up with the idea to add default values for the query parameters:
@Location("/user")
data class UserRoute(val page: Int? = null, val count: Int? = null) {

    @Location("/{id}")
    data class ById(val parent: UserRoute, val id: String)

}
i suppose i could even drop nullability there and provide 0 for
page
and whatever default page size should be for
count
❤️ 1
but i have a strong feeling that this should be part of official documentation because query parameters mostly tend to be optional
at least one small example somewhere