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.
This means your @GET or @DELETE should not have @Body parameter. You can use query type url or path type url or Query Map to fulfill your need. Else you can use other method annotation.
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")
In simple word make method over loading. Create two method with same name and different parameter. Check my below source code. (written in kotlin)
@GET("myportal/news/{id}")
fun getNewsList(@Path("id") id: String): Call<NewsEntity>
@GET("myportal/news/{id}/{dateTime}")
fun getNewsList(@Path("id") id: Long, @Path("dateTime") dateTime: String): Call<NewsEntity>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With