Retrofit 2 — How to Add Query Parameters to Every Request

Adding query parameters to single requests is straight forward. You’re using the @Query annotation for your parameter declaration within the interface methods. This tells Retrofit to translate the provided query parameter name and value to the request and append the fields to the url. Recently, we’ve been asked how to add a query parameter to every request using an interceptor. If you’re having that same problem? This post is for you!

Retrofit Series Overview

Add Query Parameters

If you’ve used Retrofit before, you’re aware of the @Query annotation used to add query parameters for single requests. There are situations where you want to add the same query parameter to every request, just like adding an Authorization header to every request passing the authentication token. If you’re requesting an API which accepts an apikey as a request parameter, it’s valuable to use an interceptor instead add the query parameter to every request method.

You can do that by adding a new request interceptor to the OkHttpClient. Intercept the actual request and get the HttpUrl. The http url is required to add query parameters since it will change the previously generated request url by appending the query parameter name and its value.

The following code illustrates the interceptor and we’ll explain the details below the snippet.

OkHttpClient.Builder httpClient =  
    new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {  
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        HttpUrl originalHttpUrl = original.url();

        HttpUrl url = originalHttpUrl.newBuilder()
                .addQueryParameter("apikey", "your-actual-api-key")
                .build();

        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                .url(url);

        Request request = requestBuilder.build();
        return chain.proceed(request);
    }
});

Once you’ve the HttpUrl object, you can create a new builder based on the original http url object. The builder will let you add further query parameters using the .addQueryParameter(key, val) method. Once you’ve added your query parameter, use the .build() method to create the new HttpUrl object which is added to the request by using the Request.Builder. The code above builds the new request with the additional parameter based on the original request and just exchanges the url with the newly created one.

Outlook

The shown functionality to add request parameters within the OkHttp interceptor isn’t that obvious. If your API requires you to send the same query parameter with every request, it’s a very convenient way to shift the query parameter definition from the interface methods to a request interceptor.

Explore the Library

Find interesting tutorials and solutions for your problems.