Retrofit — Multiple Query Parameters of Same Name

This post belongs to our Retrofit series and describes how to perform requests with single and multiple query parameters of same name. The following overview illustrates the posts from mentioned series.

Retrofit Series Overview

  1. Introduction to Call Adapters (Coming soon)
  1. Callbacks (Coming soon)
  2. Annotations (Coming soon)
  3. Fluent Interface with Builders (Coming soon)

Query Parameters

Query parameters are a common way to pass data from clients to servers. We all know them for requests. Let's face the example below which requests a specific task with id=123 from our example API.

https://api.example.com/tasks?id=123  

The response from example API is only a single task with id=123.

The Retrofit method definition for query parameters is straight forward.

Retrofit 2

public interface TaskService {  
    @GET("/tasks")
    Call<Task> getTask(@Query("id") long taskId);
}

Retrofit 1.9

public interface TaskService {  
    @GET("/tasks")
    Task getTask(@Query("id") long taskId);
}

The method getTask(…) requires the parameter taskId. This parameter will be mapped by Retrofit to given @Query() parameter name. In this case the parameter name is id which will result in a final request url part like

/tasks?id=<taskId>

Multiple Query Parameters

Some use cases require to pass multiple query parameters of the same name. Regarding the previous example of requesting tasks from an API, we can extend the query parameter to accept a list with multiple task ids.

The request url we want to create should look like

https://api.example.com/tasks?id=123&id=124&id=125  

The expected server response should be a list of tasks with the given ids=[123, 124, 125] from url query parameters.

The Retrofit method to perform requests with multiple query parameters of the same name is done by providing a list of ids as a parameter. Retrofit concatenates the given list to multiple query parameters of same name.

Retrofit 2

public interface TaskService {  
    @GET("/tasks")
    Call<List<Task>> getTask(@Query("id") List<Long> taskIds);
}

Retrofit 1.9

public interface TaskService {  
    @GET("/tasks")
    List<Task> getTask(@Query("id") List<Long> taskIds);
}

The resulting request url will look like the example above in the beginning of this section (Multiple Query Parameters).

If you run into questions or problems, find us on Twitter @futurestud_io or in the comment section below.

Enjoy coding & make it rock.


Explore the Library

Find interesting tutorials and solutions for your problems.

Miscellaneous