Search code examples
androidkotlinktorkotlin-multiplatformktor-client

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


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?


Solution

  • From official docs

    DefaultRequest allows you to configure a base part of the URL that is merged with a request URL.

    defaultRequest {
        url("https://ktor.io/docs/")
    }
    

    If you make the following request using the client with the above configuration, ...

    val response: HttpResponse = client.get("welcome.html")
    

    ... the resulting URL will be the following: https://ktor.io/docs/welcome.html