Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 598
RafalManka Avatar asked Nov 28 '16 19:11

RafalManka


People also ask

How do you pass body in GET request retrofit on Android?

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.


Video Answer


2 Answers

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")

like image 52
Beloo Avatar answered Sep 24 '22 13:09

Beloo


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>
like image 21
Hitesh Dhamshaniya Avatar answered Sep 23 '22 13:09

Hitesh Dhamshaniya