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.
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.
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.
Create a function in the viewmodel class and pass the parameter in the function itself, then make the service call from that funciton.
Just put it right in the relative URL:
public interface YoutubeApi {
@GET("oembed?format=json")
YoutubeMetaData metaData(@Query(QUERY_VIDEO_URL) String url);
}
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>
}
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