Ktor fundamentals on shopper facet. An alternate means for Retrofit on… | via Enmanuel Delgado | Feb, 2024

An alternate means for Retrofit on Android

Creation:

Ktor is a light-weight multi-platform framework for development asynchronous server facet and shopper facet programs the usage of the overall energy of Kotlin and coroutines.

Certainly, is the principle choice for Kotlin multi-platforms tasks.

Let’s dive within the shopper facet, via an open supply undertaking I’ve been growing.

The right way to use:

First than all you want to create an HttpClient and go an engine as parameter:

val ktorClient = HttpClient(CIO)

When engine is skipped it is going to make a selection one robotically, this turns out to be useful for multi-platform tasks.

You’ll configure the buyer right here via putting in plugins and configuring them:

val ktorClient = HttpClient(CIO) {
defaultRequest {
url(BASE_URL)
url {
parameters.append(identify = "api_key", price = BuildConfig.API_KEY)
}
headers {
appendIfNameAbsent("X-CustomHeader", "Some header")
}
}

set up(HttpTimeout) {
requestTimeoutMillis = 10000L
}
}

I to find DefaultRequest specifically usefully as a result of lets in so as to add data required for every request.

Engines: lets in Ktor to processes community requests for explicit platforms.

Plugins: supplies Ktor not unusual capability like serialization, logging, authentication.

Making requests:

As soon as HttpClient has been configured making requests is so simple as this:

typealias KtorClient = HttpClient

elegance MovieService(non-public val httpClient: KtorClient) {

droop amusing getTopRatedMovies(web page: Int) = httpClient
.get("film/top_rated") {
url {
parameters.append(identify = "web page", price = "$web page")
}
}
}

There are purposes for get, publish, put, delete, patch and so forth. As you’ll see you’ll make configurations for each unmarried request as smartly.

Serialization:

In retrofit we should use some serialization library to serialize/ deserialize JSON information.
As you most likely guessed Ktor calls for a plugin to reach this behaviour, ContentNegotiation, in conjunction with the serialization library:

set up(ContentNegotiation) {
json(
Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
explicitNulls = false
}
)
}

That is how the asked data seems like:

@Serializable
inside information elegance MoviePageDTO(
@SerialName("web page")
val web page: Int,
@SerialName("effects")
override val effects: Record<MovieDTO>,
@SerialName("total_pages")
override val totalPages: Int,
@SerialName("total_results")
val totalResults: Int
):PagingResponse<MovieDTO>

Then we will replace the flicks request:

droop amusing getTopRatedMovies(web page: Int): MoviePageDTO = httpClient
.get("film/top_rated") {
url {
parameters.append(identify = "web page", price = "$web page")
}
}
.frame()

Right here, I display you a publish instance:

droop amusing deleteMovieFromList(
mediaBody: MediaOnListBody,
listId: Int,
sessionId: String,
): WatchResponseDTO = httpClient
.publish("checklist/$listId/remove_item") {
url {
parameters.append("session_id", sessionId)
}
contentType(ContentType.Software.Json)
setBody(mediaBody)
}
.frame()

Filling the blanks:

In the event you require shape parameters:

droop amusing submitForm(
e mail: String,
password: String,
) = httpClient.publish("shape"){
parameters {
append("e mail", e mail)
append("password", password)
}
}

For add recordsdata (document instance):

droop amusing putAvatar() = httpClient.put("avatar") {
setBody(
MultiPartFormDataContent(
formData {
append("description", "avatar symbol")
append(
key = "avatar",
price = Report("ktor_logo.png").readBytes(),
headers = Headers.construct {
append(HttpHeaders.ContentType, "symbol/png")
}
)
}
)
)
}

I’m hoping you guys to find this newsletter helpful and inspire you to deep dive on this improbable framework.

For more info:

Connect to me:

https://www.linkedin.com/in/enmanuel-delgado52

Leave a Comment

Your email address will not be published. Required fields are marked *