Should I pass my APIKEY in every request I do with Retrofit?

Viewed 2106

I'd like to know the best way to put my APIKEY in all my REST requests withtout having to add it in parameters of the request.

For now I just have a couple of calls, but I'm trying to see further.

@GET(".")
fun getSearch(@Query("s") text: String, @Query("apikey") APIKEY: String) : Observable<ResponseSearch>

I was wondering if there was a way not to have the APIKEY in variables of every call

3 Answers

You can, but the better solution is to use Okhttp Interceptors

Here's an example:

class TokenInterceptor(private val preferencesStorage: SharedPreferencesStorage) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var original = chain.request()
        val token = preferencesStorage.getAccessToken()
        val url = original.url().newBuilder().addQueryParameter("apikey", token).build()
        original = original.newBuilder().url(url).build()
        return chain.proceed(original)
    }
}

You should also add TokenInterceptor to your Okhttp client builder

val client = OkHttpClient.Builder()
            .addInterceptor(TokenInterceptor(SharedPreferencesStorage()))
            .build() 

It's better to have a middleware for your requests, where all queries passed through it, and there you will have a single point of adding the APIkey, also i would prefer it to add it to the header instead of query parameters

More "modern" way to achieve it

private fun apiKeyAsQuery(chain: Interceptor.Chain) = chain.proceed(
        chain.request()
            .newBuilder()
            .url(chain.request().url.newBuilder().addQueryParameter("api-key", ApiKey).build())
            .build()
    )

private fun apiKeyAsHeader(it: Interceptor.Chain) = it.proceed(
    it.request()
        .newBuilder()
        .addHeader("api-key", ApiKey)
        .build()
)

...
.client(
    OkHttpClient.Builder()
        .addInterceptor { apiKeyAsQuery(it) }
        // Or
        .addInterceptor { apiKeyAsHeader(it) }
        .build()
)
...

Related