Search code examples
androidapigetretrofit

Dynamically setting the @GET statement with retrofit


A sample request to an API is this

https://api.example.com/api/3.0/song/{song_id}.json?apikey={your_api_key}

So, in my activity

//retrofit
final Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(C.BASE_URL_DETAIL)     // "https://api.example.com/api/3.0/song/"                                           
    .addConverterFactory(GsonConverterFactory.create())
    .build();
SongInterface request = retrofit.create(SongInterface.class);
//call
Call<SongObject> call =request.getDetails(C.MY_API_KEY);

My interface for song id = 10973

@GET("10973.json?")
Call<SongObject> getDetails(
        @Query("apikey") String key
);

It works just fine and i receive the data as expected. However, I can't figure out how to call another song with another id and reuse the code. Can I somehow add the ID as a Query parameter? (the API doesn't seem to be set up to allow this). How can I dynamically update the String to the interface inside the @GET. My attempts to accomplish this have all ended with errors.


Solution

  • Hey there yes right it is absolutely correct way so send "GET" request and like you asked to get a data with respective id here is how you can achieve it

    @GET("{songId}.json?")
     Call<SongObject> getDetails(
        @Path("songId") String songId, 
        @Query("apikey") String key
     );
    

    After this you can call it simply you did it.

    LIKE THIS

    Call<SongObject> call = request.getDetails(YOUR_SONG_ID,C.MY_API_KEY);