Skip to main content

Optional Path Parameter Retrofit Service

https://futurestud.io/tutorials/retrofit-optional-path-parameters


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.

Comments

Popular posts from this blog

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App § ...

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap th...

Circular Button with Icon and Text in Android

Circular Button with Icon and Text in Android Rounded android button can be used for many purposes to make awesome application. We can see many applications that have used circle button or rounded corner. In this tutorial, I am going to show how to make circular android button and to add icons/images and text in the same button. To make circular button in android app, you don’t need any java code, this can be done by using only XML. Rounded button can also be created by using java code but it is time consuming and need to have advance knowledge of java programming. Here you will learn to make circular/rounded corner button using XML only. Related: Android Button with Icon and Text Adding Badge (Item Count) to Android Button Android Switch Button Example Android Example: How to Create Circular Button with Icon and Text in Android First you have to create a new XML file in drawable folder to make rounded button. In this file I have made a rectangle and gave border radius to ma...