Skip to content

Instantly share code, notes, and snippets.

@moallemi
Created June 1, 2023 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moallemi/f32e4610a6493effc44369aed2f37077 to your computer and use it in GitHub Desktop.
Save moallemi/f32e4610a6493effc44369aed2f37077 to your computer and use it in GitHub Desktop.
Grid Challenge API Helper for Android
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
}
}
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