RafalManka RafalManka - 8 months ago 53
Android Question

Android Retrofi2 optional @Path param

In my andorid app I am making a GET request using Retrofit2:


But I would also like to make another request e.g.


So the filter parameter is optional. I am trying to do the following:

Observable<ResponseItems> getItems(@Path("filter") String filter);

and calling it like:




But it does not work. So I ended up creating two separate service calls, one with filter param and other without. I think that there should be more elegant method though.

Answer Source

So i've seen what you are trying to achieve.

How your api declaration should looks like:

Observable<ResponseItems> getItems(@Path(value = "filter", encoded = true) String filter);

and a call service.getItems("") would lead to http://myapi.com/items/list/ be called
a call service.getItems("filter/active:true,min_price:100") would lead to http://myapi.com/items/list/filter/active:true,min_price:100 be called.

An encoded property in @Path annotation is set because your optional path parameter contains / and retrofit encodes it without that property.

So as i wrote in comments better use two declarations:

Observable<ResponseItems> getItems();

Observable<ResponseItems> getItems(@Path(value = "filter") String filter);

so you may call it like service.getItems("active:true,min_price:100")