Retrofit — Optional Query Parameters

The previous post guided you through the options to add custom headers to your requests. Today, we’re diving into the topic on how to use Retrofit to make request parameters optional.

Retrofit Series Overview

Query Parameters with Retrofit

Retrofit uses annotations to define query parameters for requests. The annotation is defined before method parameters and specifies the request parameter name. The desired value for this parameter is passed during method call. Let's face a concrete example. The code below illustrates a request method which has /tasks as API endpoint url and provides the option to pass a sort parameter for desired sorting.

Retrofit 2

public interface TaskService {  
    @GET("/tasks")
    Call<List<Task>> getTasks(@Query("sort") String order);
}

Retrofit 1.9

public interface TaskService {  
    @GET("/tasks")
    List<Task> getTasks(@Query("sort") String order);
}

Assuming that your base url to your API is https://your.api.com, the request using the TaskService from above and calling the getTasks method results in this request url: https://your.api.com/tasks?sort=value-of-order-parameter

Optional Query Parameters

Depending on the API design, the sort parameter might be optional. In case you don’t want to pass it with the request, just pass null as the value for order during method call.

service.getTasks(null);  

Retrofit skips null parameters and ignores them while assembling the request. Keep in mind, that you can’t pass null for primitive data types like int, float, long, etc. Instead, use Integer, Float, Long, etc and the compiler won’t be grumpy.

The upcoming example depicts the service definition for the previously mentioned data types.

Retrofit 2

public interface TaskService {  
    @GET("/tasks")
    Call<List<Task>> getTasks(
        @Query("sort") String order,
        @Query("page") Integer page);
}

Retrofit 1.9

public interface TaskService {  
    @GET("/tasks")
    List<Task> getTasks(
        @Query("sort") String order,
        @Query("page") Integer page);
}

Now you can pass null for either of the defined query parameters order and page when calling the getTasks method.

service.getTasks(null, null);  

Summary

In this tutorial you've seen how you can use optional query parameters.

Please let us know about any problems you ran into on Twitter @futurestud_io or in the comment section below.

Enjoy coding & make it rock!


Additional Ressources


Explore the Library

Find interesting tutorials and solutions for your problems.