Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a retrofit REST endpoint with constant query value

Tags:

java

retrofit

So I want to get the metadata of a youtube video (say this one: https://www.youtube.com/watch?v=qlTA3rnpgzU).

I'm going to encode it and wrap it in another url like so: http://www.youtube.com/oembed?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqlTA3rnpgzU&format=json

My interface definition will look like this:

public interface YoutubeApi {
    @GET ("oembed") 
    YoutubeMetaData metaData (@Query (QUERY_VIDEO_URL) final String url,
                              @Query(QUERY_FORMAT) final String alwaysJson);
}

That's all fine and dandy, but I don't ever want to specify any format other than JSON here (format=json is a fixed part of this url).

Is there a way to specify this in my interface declaration and reduce my interface to:

public interface YoutubeApi {
    @GET ("oembed") 
    @Magic ("format=json")
    YoutubeMetaData metaData (@Query (QUERY_VIDEO_URL) final String url);
}

Thanks.

like image 649
copolii Avatar asked Jun 06 '14 01:06

copolii


People also ask

How do I add a query parameter to retrofit?

Adding query parameters to single requests is straight forward. You're using the @Query annotation for your parameter declaration within the interface methods. This tells Retrofit to translate the provided query parameter name and value to the request and append the fields to the url.

What is query annotation in retrofit?

Retrofit uses annotations to define query parameters for requests. The annotation is defined before method parameters and specifies the request parameter name. The desired value for this parameter is passed during method call.

How do you pass parameters in retrofit Kotlin?

Create a function in the viewmodel class and pass the parameter in the function itself, then make the service call from that funciton.


2 Answers

Just put it right in the relative URL:

public interface YoutubeApi {
  @GET("oembed?format=json") 
  YoutubeMetaData metaData(@Query(QUERY_VIDEO_URL) String url);
}
like image 148
Jake Wharton Avatar answered Oct 16 '22 16:10

Jake Wharton


In kotlin you can specify the default parameter:

interface YoutubeApi {

    @GET ("oembed") 
    suspend fun metaData (
        @Query (QUERY_VIDEO_URL) url: String,
        @Query(QUERY_FORMAT) alwaysJson: String = "json"
    ): Response<YoutubeMetaData>

}
like image 44
Haider Malik Avatar answered Oct 16 '22 18:10

Haider Malik