How to set a basePath in Ktor similar to Retrofit's `Retrofit.Builder().baseUrl(baseUrl)?

Viewed 2282

I am trying out Ktor by converting some existing project that's currently using Retrofit.

Although I could easily convert the request into something like:

client.get {
    url("$BASE_URL/something/somepage/another")
}

It seems very tedious to always add the $BASE_URL to all paths every time. In retrofit, we could simply do something like:

Retrofit.Builder()
    .baseUrl(BASE_URL)
    .create(SomeServiceClass::class.java)

I've triede using defaultRequest and setting the BASE_URL there but apparently you could only set the url.host and not the whole basePath.

Is there a way to do the same thing in Ktor? or if there is none, what's the best practice to handle this?

1 Answers

You can!

In order to do so you need to set your default request when you instantiate your client.

val httpClient = HttpClient(Android) {
        defaultRequest {
            host = "my.zoo.com"
            url {
                protocol = URLProtocol.HTTPS
            }
        }
    }

val response = httpClient.get<List<CatsResponse>>(
        path = "animals/cats"
)

This will call https://my.zoo.com/animals/cats

Hope it helps :)

Related