Networking

Learn how to perform HTTP requests and map them into objects

Android Blaze uses Ktor’s HttpClient to perform http requests. It provides a simple, yet flexible way to perform HTTP requests.

 

We provide the httpClient() function to gain access to the HttpClient. Creating new http clients is not a cheap operation. Because of this, the httpClient() will always return the same instance, as recommended in the Ktor documentation.

 

Making a basic HttpRequest

This example showcase how to perform a GET request to the Unsplash API to get random images. The Unsplash API requires an Api Key for authentication. The sample shows how to edit the request and dynamically add the required Authorization header into the request:

val httpClient = httpClient()
val response = client.get(
    "https://api.unsplash.com/photos/random?query=landscape&count=100"
) {
    headers {
        append("Authorization", "Client-ID $UNSPLASH_API_KEY")
    }
}
 

You can configure Ktor to include this header in every request instead. Learn how by checking Ktor’s Documentation.

Mapping Http responses to data classes

Android Blaze uses Ktor HttpClient in combination with Kotlin’s Serialization to map your HTTP responses to data classes.

Create your data classes and annotate them with @Serializable:

import kotlinx.serialization.Serializable

@Serializable
data class ApiPhoto(
    val id: String,
    val description: String?,
    val alt_description: String,
    val urls: Urls,
    val views: Long,
)

@Serializable
data class Urls(
    val raw: String,
    val full: String,
    val regular: String,
    val small: String,
    val thumb: String,
    val small_s3: String,
)
 

and then use .body() with the expected type to map the response to the respective object:

val response = httpClient().get(
    "https://api.unsplash.com/photos/random?query=landscape&count=100"
){
	headers {
			append("Authorization", "Client-ID $UNSPLASH_API_KEY")
	}
}

val apiPhotos = response.body<List<ApiPhoto>>()
 
⚠️
Make sure to move your data classes used in networking in the .apimodels package. In release builds, your code will be obfuscated and minimized using Proguard. This will prevent your models to be mapped successfully. The contents of the .apimodels package will not be obfuscated in release builds.
Did this answer your question?
😞
😐
🤩