Connect to Unsplash API Using OkHttp on Android

July 12, 2019

Create an Unsplash Developer Account, create an app (for access key and secret key).

  • By default, it only allows 50 request per hour.
  • To get 5000 requests per hours, you need to meet the following guidelines and terms.

NOTE:

Your application’s Access Key and Secret Key must remain confidential. This means that they cannot be included in the client or made public. In most cases, this will require proxying the API through your own endpoint to sign the request with your keys.

So storing Access Key in Android to access the API might not be a good idea.

Install OkHttp dependencies.

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.0.1'
}

NOTE: Proguard Configuration

Unsplash helper class.

class UnsplashHelper {

    companion object {
        private const val BASE_URL = "https://api.unsplash.com"
        private const val ACCESS_KEY = "6a9c..."
        // private const val SECRET_KEY = "966b..."

        // val instance: UnsplashHelper by lazy { UnsplashHelper() }

        // https://unsplash.com/documentation#dynamically-resizable-images
        const val SIZE_SMALL = "fm=webp&w=400&fit=max"
        const val SIZE_FULL = "fm=webp&w=1600&fit=max"
    }

    fun getImageUrl(url: String, size: String): String {
        return "$url&$size"
    }

    // https://unsplash.com/documentation#get-a-photo
    fun getPhotoUrl(id: String): String {
        val path = "/photos/$id"
        val uri = Uri.parse(BASE_URL)
            .buildUpon()
            .appendEncodedPath(path)
            //.appendPath(path)
            .build()

        val client = OkHttpClient()
        val request = Request.Builder()
            .url(uri.toString())
            .addHeader("Accept-Version", "v1")
            .addHeader("Authorization", "Client-ID $ACCESS_KEY")
            .get()
            .build()

        val response = client.newCall(request).execute()
        val jsonDataString = response.body()?.string()

        val json = JSONObject(jsonDataString)
        if (!response.isSuccessful) {
            val errors = json.getJSONArray("errors").join(", ")
            throw Exception(errors)
        }
        val rawUrl = json.getJSONObject("urls").getString("raw")
        return rawUrl
    }
}

Usage

val unsplash = UnsplashHelper()
val rawUrl = unsplash.getPhotoUrl("SBK40fdKbAg")
val url = unsplash.getImageUrl(rawUrl, UnsplashHelper.SIZE_SMALL)

NOTE: Load remote url image via Fresco.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.