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);
Related
Cannot get the API request to work with the API key. Have already tested it with a different API that doesn't use an API Key, which has worked. Makes me think that I'm not adding the API Key properly.
Tested it on postman using the authentication tab which works well.
How can I send the key Access-Key and value 9xxxxxxxxxxxxx3 using retrofit2?
code
When you call R.string.api_key, you don't get the String value, you only get its id, which is represented as a number. To get the value you need to have context and call context.getString(R.string.api_key). In our case, it is better to take it out from string.xml and place it in some class.
For example
object Constants {
const val BASE_URL = "http://test.com/"
}
and then inside the retrofit
return Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
but if you want to get the value from string.xml you need to change getInstance() method from example add Context.
You can send Headers like as:
public interface APIService {
//Login
#FormUrlEncoded
#POST("loginAction")
Call<LoginModel> loginMI(
#Field("username") String username,
#Field("pwd") String pwd,
#Header("api_key") String api_key,
#Header("secret_key") String secret_key
);
}
call the above API and pass the required Field and Headers.
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);
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.
I have a web-service method called change. I send UpdateStatusRequest objects to this web-service which defined as below:
public class UpdateStatusRequest {
private String Status;
public UpdateStatusRequest(String status) {
Status = status;
}
public String getStatus() {
return Status;
}
}
When I use below API deceleration:
#POST("StatusUpdate")
Call<Status> change(#Query("Status") String status);
and then calling statusApi.change(request.getStatus()), it works well. It will call http://server-url/StatusUpdate?Status=Ready, when I pass Ready as status.
But using below declaration
#POST("StatusUpdate")
Call<Status> change(#Body UpdateStatusRequest status);
and then calling statusApi.change(request), it will call http://server-url/StatusUpdate and sends Status in request body. This will lead to 404 status code with error prompt Not Found.
I want to know what's wrong with my second call (since I supposed #Body acts like several #Query parameters which bundled together in the same object)?
In Retrofit,
#Body doesn't same as #Query.
#Body – Sends Java objects as request body.
#Query- Query parameter appended to the URL.null values are ignored.
But #Field is almost similar to #Body tag.
#Field – Send data as form-urlencoded. The #Field parameter works only with a POST.
For Example:
#POST("StatusUpdate")
Call<Status> change(#Field("Status") String Status);
But in your case, Your server is expecting the params to be passed in
the URL(#Query).
Hope this explanation help.
#Body doesn't act like several #Query parameters. These are two different ways of sending data in a request.
The differences are pretty much already described in your question. With #Query,it will append the URL with the query params you pass, as in http://server-url/StatusUpdate?Status=Ready. Instead, if you use #Body, the params will be added to the body request, so your URL will have no params, as in http://server-url/StatusUpdate, and your body request will be Status=Ready.
Based on the results you got, your server is expecting the params to be passed in the URL(#Query).
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.