Dynamically add optional parameters to API requests
android, retrofit
Solution
You have a few ways to achieve that:
By default Retrofit handles nulls correctly for all null query parameters, so you can do something like:
@GET("/user/{id}/likes")
void getLikes(@Path("id") int id, @Query("n") Integer number, @Query("pos") Integer pos Callback<String> cb);
If you use Object instead of int you can call to the method using null for the optional parameters:
getLikes(1, null, null, cb); // to get /user/1/likes
getLikes(1, 2, null, cb); // to get /user/1/likes?n=2
By using RequestInterceptor:
RestAdapter.Builder builder= new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json;versions=1");
if(/*condition*/){
request.addQueryParam(arg0, arg1)
}
}
});
Problem
I have an Android app that communicates with a REST API. For each request, I want my app to be able to add optional parameters in addition to the mandatory parameters. How can I implement this with Retrofit? Currently all the parameters are hard-coded in the interface: ``` @GET("/user/{id}/comments?position={pos}") void getComments(@Path("id") int id, @Query("pos") int pos, Callback<String> cb); @GET("/user/{id}/likes?n={number}") void getLikes(@Path("id") int id, @Query("number") int number, Callback<String> cb); /* etc */ ``` Is it possible to "sub-class" the `RestAdapter` or something to be able to dynamically add optional parameters to my requests?