user513590
user513590

Reputation: 117

Example of URL builder in Ktor

I'm using Ktor client to make calls to an API and I didn't find any examples of how to construct a URL with query parameters.

I wanted something like this:

protocol = HTTPS,
host = api.server.com,
path = get/items,
queryParams = List(
  Pair("since", "2020-07-17"),
  
)

I can't find any examples of how to use URL builder for this.

Upvotes: 4

Views: 8402

Answers (2)

Sina Rahimi
Sina Rahimi

Reputation: 321

It would also be helpful if someone wants to add a base URL to all their requests :

 HttpClient(Android) {

        expectSuccess = false

        //config Client Serialization
        install(JsonFeature) {
            serializer = KotlinxSerializer(json)
        }

        //config client logging
        install(Logging) {
            level = LogLevel.BODY
        }

        //Config timeout
        install(HttpTimeout) {
            requestTimeoutMillis = 30 * 1000L
            connectTimeoutMillis = 10 * 1000L
        }

        //Config Base Url
        defaultRequest {
            url {
                protocol =URLProtocol.HTTPS
                host = baseUrl
            }
        }
    }

  val json = kotlinx.serialization.json.Json {
    ignoreUnknownKeys = true
    isLenient = true
    encodeDefaults = false
}

Upvotes: -1

szymon_prz
szymon_prz

Reputation: 560

If you want to specify each of this element (protocol, host, path and params) separately you can use a HttpClient.request method to construct your url. Inside this method you have access to HttpRequestBuilder and then you can configure url with usage of UrlBuilder

client.request<Response> {
            url {
                protocol = URLProtocol.HTTPS
                host = "api.server.com"
                path("get", "items")
                parameters.append("since", "2020-07-17")
            }
        }

Response type is your response, you can specify there whatever you need

Upvotes: 12

Related Questions