RafalManka RafalManka - 9 days ago 5
Android Question

Android Retrofit2 optional @Path param

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

http://myapi.com/items/list


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

http://myapi.com/items/list/filter/active:true,min_price:100


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

@GET("items/items/list{filter}")
Observable<ResponseItems> getItems(@Path("filter") String filter);


and calling it like:

service.getItems("")


and:

service.getItems("/filter/active:true,min_price:100")


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

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

How your api declaration should looks like:

@GET("items/list/{filter}")
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:

@GET("items/list/")
Observable<ResponseItems> getItems();

@GET("items/list/filter/{filter}")
Observable<ResponseItems> getItems(@Path(value = "filter") String filter);

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