Retrofit query parameters - android

I need to get movies from OMBD api database.
In main activity I have recycler view and toolbar with menu item search implemented by widget SearchView.
I need to type the title of the movie in the search menu item and send that request to the server
I have url like this https://omdbapi.com/?s=title&apikey=123456bb where title should be inserted by the user via search menu item.
I want to ask how can I define the endpoints using retrofit when my base url is:http://omdbapi.com
#GET("https://www.omdbapi.com")
Call<Movie> search(#Query("s") String keyword, #Query("apikey") String apikey);
Something like this?

You define your base url when you are creating your Retrofit instance:
final OMBDApi api = new Retrofit.Builder()
.baseUrl("https://omdbapi.com/")
.build()
.create(OMBDApi.class);
Inside the #Get (or other interface methods) you just put the relative path. If you have fixed query parts, you can just throw them in the relative url:
#Get("?apikey=<your_api_key>")
Call<Movie> search(#Query("s") String keyword);

Related

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.
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);

How to call dotnet api from Retrofit?

This day is the first time for me to use dotNet web API for my project.
This is the code of my controller
public IEnumerable<Waybill> Get(string id_wb) {
List<Waybill> lstWaybill = new List<Waybill>();
lstWaybill = objway.GetWaybill(id_wb).ToList();
return lstWaybill;
}
That API can work well if I'm call using this link :
http://localhost:56127/api/waybill/?id_wb=00000093
but I don't know how to call that link from my android app (I'm using retrofit)
#GET("Waybill/{id_wb}/id_wb")
Call<Waybill> getWaybillData(#Path("id_wb") String id_wb);
There are 3 options.
First one is to use Retrofit's #Query annotation.
#GET("Waybill/")
Call<Waybill> getWaybillData(#Query("id_wb") String id_wb);
The second one is to #Path annotation
#GET("Waybill/?id_wb={id_wb}") // notice the difference in your code and my code
Call<Waybill> getWaybillData(#Path("id_wb") String id_wb);
The third option is to use #Url annotation. With this option, you need to prepare fully qualified URL before calling/using getWaybillData() method in your activity or fragment. Keep in mind that #Url method overrides base URL set in Retrofit client.
#GET // notice the difference in your code and my code
Call<Waybill> getWaybillData(#Url String completeUrl);
If you follow 3rd option you need to prepare full URL in your activity like below.
String url = "http://<server_ip_address>:56127/api/waybill/?id_wb=00000093";
YourInterface api = ...
Call<Waybill> call = api.getWaybillData(url);
call.enqueue({/* implementation */});
I see a difference in the sample URL you mentioned and usage in Retrofit API interface.
In sample URL waybill is small and in API interface it is Waybill. Please ensure that you're using the right URL.

Call Twitter Endpoint API to follow another user Android

I'm using Twitter end point API to follow another user. The API is:
https://api.twitter.com/1.1/friendships/create.json?follow=&screen_name=&user_id=
with Authorization header passed as:
#Headers("Authorization: OAuth oauth_consumer_key=DC0sePOBbQ8bYdC8Smg,oauth_signature_method=HMAC-SHA1,oauth_timestamp=1502774524,oauth_nonce=175308858,oauth_version=1.0,oauth_token=712057165-iQB4b4Q0hsNmHsAxiW4X5UF5xVB6JmKOPhxnW,oauth_signature=X0GExH5DBVgVv49jkO3LwfX8%3D")
#POST()
#FormUrlEncoded
Call<ResponseBody> followUser(#Url String url, #Field("follow") boolean follow, #Field("screen_name") String screenName, #Field("user_id") String userId);
in Retrofit API call from Android. This works fine. But the Auth header has to be generated dynamically for every logged in user. How to achieve that?
You can use #Header annotation in parameter list. Please check the official documentation.
Replaces the header with the value of its target.
#GET("/")
Call<ResponseBody> foo(#Header("Accept-Language") String lang);
Header parameters may be null which will omit them from the request.
Passing a List or array will result in a header for each non-null
item.
Note: Headers do not overwrite each other. All headers with the same
name will be included in the request.

what is the difference between #Query and #path in Retrofit?

I wanted to use retrofit library for parsing and posting the data by passing some parameters. But When defining model class some times we will use #Serialized in-front of variable, What is the use of that Serialized.And What is the difference between #Get and #Query in passing params to API.Can Any one explain the difference.
Lets say you have api method #GET("/api/item/{id}/subitem/") so by using #Path("id") you can specify id for item in path. However your api may take additional parameters in query like sort, lastupdatetime, limit etc so you add those at end of url by #Query(value = "sort") String sortQuery
So full method will look like:
#GET("/api/item/{id}/subitem")
SubItem getSubItem(#Path("id") int itemId, #Query("sort") String sortQuery, #Query("limit") int itemsLimit);
and calling api.getSubItem(5, "name", 10) will produce url #GET("/api/item/5/subitem/?sort=name&limit=10")
and #Get is HTTP method
http://www.w3schools.com/tags/ref_httpmethods.asp says
Two commonly used methods for a request-response between a client and
server are: GET and POST.
GET - Requests data from a specified resource POST - Submits data to
be processed to a specified resource
#GET is request method. You mark method with that.
#Query is query parameter (i.e. the one in the URL). You mark method parameters with that.
#Serialized probably does not belong to Retrofit, look at its package name (move cursor there and press `Ctrl+Q in Android studio)

Why is Retrofit adding a trailing slash to all URLs?

Editing question with more details :
I understand the use of service interfaces in Retrofit. I want to make a call to a URL like this :
http://a.com/b/c (and later append query parameters using a service interface).
My limitations are :
I cannot use /b/c as a part of service interface (as path parameter). I need it as a part of base url. I have detailed the reason below.
I cannot afford to have a resultant call being made to http://a.com/b/c/?key=val. What I need is http://a.com/b/c?key=val (the trailing slash after "c" is creating problems for my API). More details below.
My Server API changes pretty frequently, and I am facing trouble on the client side using Retrofit. The main problem is that we cannot have dynamic values (non final) passed to #GET or #POST annotations for Path Parameters (like it is possible for query parameters). For example, even the number of path parameters change when the API changes. We cannot afford to have different interfaces everytime the API changes.
One workaround to this is by forming the complete URLs, that is, an Endpoint with Base_Url + Path_Parameters.
But I am wondering why is Retrofit forcibly adding a trailing slash ("/") to the base url :
String API_URL = "https://api.github.com/repos/square/retrofit/contributors";
if (API_URL.endsWith("/")) {
API_URL = API_URL.substring(0, API_URL.length() - 1);
}
System.out.println(API_URL); //prints without trailing "/"
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.build();
API_URL is always being reset to https://api.github.com/repos/square/retrofit/contributors/ by Retrofit internally (confirmed this by logging the request)
One workaround to this is by manually adding a "?" in the end to prevent "/" to be added: https://api.github.com/repos/square/retrofit/contributors?
Unfortunately, such request won't be accepted by our API.
Why is Retrofit forcing this behavior ?
Is there a solution for people like me who don't want a trailing slash ?
Can we have variable parameters (non final) being passed to Retrofit #GET or #POST annotations ?
You're expected to pass the base URL to the setEndpoint(...) and define /repos/... in your service interface.
A quick demo:
class Contributor {
String login;
#Override
public String toString() {
return String.format("{login='%s'}", this.login);
}
}
interface GitHubService {
#GET("/repos/{organization}/{repository}/contributors")
List<Contributor> getContributors(#Path("organization") String organization,
#Path("repository") String repository);
}
and then in your code, you do:
GitHubService service = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build()
.create(GitHubService.class);
List<Contributor> contributors = service.getContributors("square", "retrofit");
System.out.println(contributors);
which will print:
[{login='JakeWharton'}, {login='pforhan'}, {login='edenman'}, {login='eburke'}, {login='swankjesse'}, {login='dnkoutso'}, {login='loganj'}, {login='rcdickerson'}, {login='rjrjr'}, {login='kryali'}, {login='holmes'}, {login='adriancole'}, {login='swanson'}, {login='crazybob'}, {login='danrice-square'}, {login='Turbo87'}, {login='ransombriggs'}, {login='jjNford'}, {login='icastell'}, {login='codebutler'}, {login='koalahamlet'}, {login='austynmahoney'}, {login='mironov-nsk'}, {login='kaiwaldron'}, {login='matthewmichihara'}, {login='nbauernfeind'}, {login='hongrich'}, {login='thuss'}, {login='xian'}, {login='jacobtabak'}]
Can we have variable parameters (non final) being passed to Retrofit #GET or #POST annotations ?
No, values inside (Java) annotations must be declared final. However, you can define variable paths, as I showed in the demo.
EDIT:
Note Jake's remark in the comments:
Worth noting, the code linked in the original question deals with the case when you pass https://api.github.com/ (note the trailing slash) and it gets joined to /repos/... (note the leading slash). Retrofit forces leading slashes on the relative URL annotation parameters so it de-dupes if there's a trailing slash on the API url.

Categories

Resources