Created
June 1, 2023 07:25
-
-
Save moallemi/f32e4610a6493effc44369aed2f37077 to your computer and use it in GitHub Desktop.
Grid Challenge API Helper for Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.withContext | |
import okhttp3.OkHttpClient | |
import okhttp3.Request | |
suspend fun fetchPhotos(): List<Photo> = withContext(Dispatchers.IO){ | |
val client = OkHttpClient() | |
val request = Request.Builder() | |
.url("https://api.unsplash.com/photos?order_by=popular&orientation=squarish&per_page=40") | |
.addHeader("Authorization", "Client-ID REPLACE_WITH_ACCESS_KEY") | |
.build() | |
client.newCall(request).execute().use { response -> | |
if (!response.isSuccessful) throw IllegalStateException("Unexpected code $response") | |
val body = response.body?.string() | |
val photos: List<Photo> = Json{ | |
ignoreUnknownKeys = true | |
}.decodeFromString(body ?: "") | |
return@use photos | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.serialization.* | |
import kotlinx.serialization.json.* | |
@Serializable | |
data class Photo(val id: String, val urls: Urls, val width: Int, val height: Int) | |
@Serializable | |
data class Urls(val regular: String) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment