https://futurestud.io/tutorials/retrofit-optional-path-parameters
Don’t Pass
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 urlhttps://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
.
Comments
Post a Comment