Retrofit — Optional Path Parameters

Requesting data from an API can include user defined filters for specific data. A common scenario is to filter a single item from its resource collection by using a query or path parameter. Depending on the API implementation, you’re probably using the same endpoint to request different data with given filter values. This blogpost will show you how use optional path parameters to refine your request for single or multiple values.

Before diving into the topic, have a look at other posts within this series.

Retrofit Series Overview

Introduction

Within this post, we’ll show code snippets that make use of a ServiceGenerator class. We’ve introduced this class in the getting started post of this Retrofit series. If you’re not familiar with the ServiceGenerator, you can catch up within the linked post.

API Description

Let’s assume we want to request a list of tasks from an API. The tasks endpoint is located at /tasks and the API implementation allows you to filter the request to a single task by passing an individual task id, /tasks/<task-id>. You’ll receive the same response format: a list of tasks. If you specify the task id, you’ll receive a list of tasks with the single item.

Optional Path Parameter

Related to the imaginary API described above, we can use the following interface to request a list of tasks and also to filter down to a single task item.

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

As you can see in the TaskService above, we’ve defined a path parameter taskId that will map its value appropriately.

The trick is this: you need to use an empty string parameter. Retrofit will map the empty string value properly as it would do with any serious value, but the result is an url without path parameters.

Look, the following urls are handled the same on server-side which allows us to reuse the endpoint for different requests:

# will be handled the same
https://your.api.url/tasks  
https://your.api.url/tasks/  

The following code snippets show you how to request the general list of tasks and how to filter down to a single task item.

// request the list of tasks
TaskService service =  
    ServiceGenerator.createService(TaskService.class);
Call<List<Task>> voidCall = service.getTasks("");

List<Task> tasks = voidCall.execute().body();  

By passing an empty String to the getTasks method, Retrofit (especially OkHttp’s HttpUrl class) will “remove” the path parameter and just use the leading url part for the request.

The code example below illustrates the request to filter a single task using the same endpoint. Because we’re now passing an actual value for the path parameter, the mapping applies and the request url contains the parameter value.

// request a single task item
TaskService service =  
    ServiceGenerator.createService(TaskService.class);
Call<List<Task>> voidCall = service.getTasks("task-id-1234");

// list of tasks with just one item
List<Task> task = voidCall.execute().body();  

That’s the trick to reuse an endpoint if the API returns data in a consistent schema.

Attention

Actually, the shown trick can cause issues as well. If your path parameter is right in the middle of the url, passing an empty string will result in a wrong request url. Let’s assume there’s a second endpoint responding with a list of subtasks for a given task.

public interface TaskService {  
    @GET("tasks/{taskId}/subtasks")
    Call<List<Task>> getSubTasks(@Path("taskId") String taskId);
}

Passing an empty value for taskId will result in the following url

https://your.api.url/tasks//subtasks  

As you can see, the API won’t be able to find the subtasks, because the actual task id is missing.

Don’t Pass Null as Parameter Value

Retrofit doesn’t allow you to pass null as a value for path parameters and if you do, it throws an IllegalArgumentException. That means, your app will crash at runtime! Be aware of this behavior with requests that involve a path parameter. Ensure stability by verifying that the path parameter values are always not null.

Outlook

This post showed you how to reuse method definitions within your service interfaces in situations where the API responses are consistent across different endpoints. You can benefit from optional path parameters to request a collection or single items from a resource using the same endpoint definition.

Be aware, that this shortcut can’t be applied to path parameters that are located in between parts of the url. Retrofit will remove path parameters with an empty value and the resulting request url probably doesn’t match your desired endpoint.

Do you have a question or comment? Just leave them below or shoot us @futurestud_io.


Explore the Library

Find interesting tutorials and solutions for your problems.