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

  1. Getting Started and Creating an Android Client
  2. Retrofit 2 — Basics of API Description
  3. Retrofit 2 — Creating a Sustainable Android Client
  4. Synchronous and Asynchronous Requests
  5. Send Objects in Request Body
  6. Add Custom Request Header
  7. Retrofit 2 — Manage Request Headers in OkHttp Interceptor
  8. Retrofit 2 — Dynamic Request Headers with @HeaderMap
  9. Multiple Query Parameters of Same Name
  10. Optional Query Parameters
  11. Using the Log Level to Debug Requests
  12. Retrofit 2 — Log Requests and Responses
  13. Retrofit 2 — Enable Logging for Development Builds Only
  14. How to Upload Files to Server
  15. Retrofit 2 — How to Upload Files to Server
  16. Retrofit 2 — How to Upload Multiple Files to Server
  17. Retrofit 2 — Passing Multiple Parts Along a File with @PartMap
  18. Basic Authentication on Android
  19. Token Authentication on Android
  20. OAuth on Android
  21. Retrofit 2 — Hawk Authentication on Android
  22. How to Refresh an Access Token
  23. Retrofit 2 — Upgrade Guide from 1.9
  24. Retrofit 2 — Simple Error Handling
  25. How to use OkHttp 3 with Retrofit 1
  26. Send Data Form-Urlencoded
  27. Send Data Form-Urlencoded Using FieldMap
  28. Retrofit 2 — How to Add Query Parameters to Every Request
  29. Retrofit 2 — Add Multiple Query Parameter With QueryMap
  30. Retrofit 2 — How to Use Dynamic Urls for Requests
  31. Retrofit 2 — URL Handling, Resolution and Parsing
  32. Retrofit 2 — Constant, Default and Logic Values for POST and PUT Requests
  33. Retrofit 2 — How to Download Files from Server
  34. Retrofit 2 — Cancel Requests
  35. Retrofit 2 — Reuse and Analyze Requests
  36. Retrofit 2 — How to Change API Base Url at Runtime
  37. Optional Path Parameters
  38. Retrofit 2 — How to Send Plain Text Request Body
  39. Retrofit 2 — Pagination Using Query Parameter
  40. Retrofit 2 — Pagination Using Link Header and Dynamic Urls (Like GitHub)
  41. Retrofit 2 — Pagination Using Range Header Fields (Like Heroku)
  42. How to Integrate XML Converter
  43. Define a Custom Response Converter
  44. Retrofit 2 — Introduction to (Multiple) Converters
  45. Retrofit 2 — Adding & Customizing the Gson Converter
  46. Retrofit 2 — Implementing Custom Converters
  47. Retrofit 2 — Basics of Mocking Server Responses
  48. Retrofit 2 — Customizing Network Behavior of Mocked Server Responses (soon)
  49. Java Basics for Retrofit — Callbacks (soon)
  50. Java Basics for Retrofit — Annotations (soon)
  51. Java Basics for Retrofit — Fluent Interface with Builders (soon)

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.

Miscellaneous