I have a list of users in parse.com
I need to retrieve some of these users, I had all of the necessary ids.
For example I had 50 users stored in parse, but I only need 10.
With these 10 Ids I need to get the users.
I postman I do the next:
https://parseapi.back4app.com/users?where={"objectId":{"$in":["id01","id02","id03".."id10"]}}
And I get the data correctly.
How can I translate into a retrofit call? How I can do a "where" sentence in Retrofit?
Thanks for all.
Try defining where as a URL parameter and setting {"objectId":{"$in":["id01","id02","id03".."id10"]}} as the value textInCurlyBrackets when using the retrofit call:
public interface FooService {
#GET("https://parseapi.back4app.com/users")
void getUsersByIDs(#Query("where") String textInCurlyBrackets, Callback<String> callback);
}
If you need further information this post may help you: Retrofit and GET using parameters
Related
I am very much new to android and I was studying the Retrofit 2 for networking, to send the Get why we are use the Query parameter?
It is not necessary to send Query Parameters with GET requests. It is something related to how the end point is configured on the API you are trying to consume.
While designing APIs especially GET methods certain parameters can be kept optional by specifying them as query parameters.
#GET("location")
Response getUser(#QueryParam("name") String name);
can be called by both
/location
/location?name=test
Query Parameter is not merely confined to GET requests. It can be used with other methods too e.g., DELETE, etc.
This is a concept related to HTTP methods
Retrofit uses annotations to translate defined keys and values into appropriate format. Using the #Query("key") String value annotation will add a query parameter with name key and the respective string value to the request url (of course you can use other types than string :)).
Actually, there are APIs with endpoints allowing you to pass (optionally) multiple query parameters. You want to avoid a service method declaration like the one below with “endless” options for request parameters:
public interface NewsService() {
#GET("/news")
Call<List<News>> getNews(
#Query("page") int page,
#Query("order") String order,
#Query("author") String author,
#Query("published_at") Date date,
…
);
}
You could call the .getNews service method with null values for each of the parameters to make them optional. Retrofit will ignore null values and don’t map them as query parameters. However, there is a better solution to work with complex API endpoints having various options for query parameters. Don’t worry, Retrofit got you covered!
You can explore more from the given link below:-
https://futurestud.io/tutorials/retrofit-2-add-multiple-query-parameter-with-querymap
Lets say you have following api to call:
https://api.themoviedb.org/3/movie/now_playing/api_key=1
So for you to pass the value for "api_key" dynamically, you should use #Query("api_key") as:
#GET("movie/now_playing")
Call<MovieData> getMovieData(#Query("api_key") String apiKey);
So here is a simple way to understand it for those that might want to use Retrofit query. Please check as follows ....
If you specify #GET("Search?one=5"), then any #Query("two") must be appended using &, producing something like Search?one=5&two=7.
If you specify #GET("Search"), then the first #Query must be appended using ?, producing something like Search?two=7.
That's how Retrofit works.
When you specify #GET("Search?"), Retrofit thinks you already gave some query parameter, and appends more query parameters using &.
Remove the ?, and you will get the desired result.
enter String BASE_URL = "https://api.test.com/";
String API_KEY = "SFSDF24242353434";
#GET("Search") //i.e https://api.test.com/Search?
Call<Products> getProducts(
#Query("one") String one,
#Query("two") String two,
#Query("key") String key
)
Result:
https://api.test.com/Search?one=Whatever&two=here&key=SFSDF24242353434
I have an Api URL. I share this item with you below. I have two things. The start and end time) How do I give these two items to the URL? So what do I have to do to find these readings in my URL? I'm gonna leave a piece of my code downstairs so you can help me out more easily. Thanks.
My URL:
report/?pageNumber=0&sortDirection=asc&startDate={startDate}&endDate={endDate}&pageSize=100
and Code Part:
#GET("report/?pageNumber=0&sortDirection=asc&startDate={startDate}&endDate={endDate}&pageSize=100")
Call<GetSalesListResponseDTO> getBetweenDatesSalesList(#Header("X-Auth-Token") String token);
If you're passing parameters into URL in GET, use #Query annotation instead of #Path
Updated code:
#GET("/api/v1/sales/report/?pageNumber=0&sortDirection=asc&pageSize=100")
Call<GetSalesListResponseDTO> getBetweenDatesSalesList(
#Header("X-Auth-Token") String token,
#Query("startDate") Long startDate, //This will append in url
#Query("endDate") Long endDate);
You can also pass other parameters pageNumber, sortDirection, pageSize like this.
More from here
I want to get list of videos from daily motion, i have registered in daily motion. it's retrieved API key and secret key but i have no idea what is the next step, i want to show the list of videos and show the detail.
I have referred https://developer.dailymotion.com/api but i could not find any way how to integrate in my application.
Please guys help to solve this!!!
In case you want to get videos only (no channel or playlist) You can simply do:
https://api.dailymotion.com/videos?page=2
Response will be paginated so you need to add page numbers
https://api.dailymotion.com/videos?page=2
You can also get more >10 results
https://api.dailymotion.com/videos?limit=100
I would recommend you to make a GET request using https://github.com/amitshekhariitbhu/Fast-Android-Networking this library and sending the API key in your request header. This is one of the best networking libraries and very easy to implement. Use .addHeaders("token", "1234") to add API key in your request.
Set up Retrofit and Moshi/Gson (Best Guide: https://guides.codepath.com/android/Consuming-APIs-with-Retrofit) and then it would be just calling an endpoint.
#GET("https://api.dailymotion.com/channel/music/videos")
Call<List<Video>> getVideos();
or
#GET("https://api.dailymotion.com/user/{userId}")
Call<List<Video>> getVideos(#Path("userId") String userId);
And to use the Access Token:
#GET("https://api.dailymotion.com/videos?")
Call<List<Video>> getVideos(#Path("userId") String userId, #Query("sort") String sort);
What is the way to send queries to Parse Server with Retrofit, rest api.
I found something like that:
trying to retrieve one object based on conditions values using Android REST API
But i don't understand how can I configure it for my kind queries in android:
#GET("classes/Mentor")
Call<OneMentorResponse> getMentor(#Query("where")
String where, #Header("X-Parse-Session-Token") String token);
pass a HashMap to query.
HashMap<String,String> sendKey=new HashMap<>;
sendKey.put("yourKey","yourValue");
yourApiInterface.getMentor(new JSONObject(sendKeyValue).toString()).new CallBack<OneMentorResponse response>{}
and implement the response and failure methods.
and also pass your header the way you are doing it.
In my application i want to store some specific data for a particular parse user and I want to fetch data from it. Should I create a class in data browser using the unique id of user or something else? Can anyone help me? Thanks in advance.
Assuming the use of the Rest API , a minimum prerequisite to exclusive READ/WRITE for a specific parse user would be to do follow:
create new user according to the parse docs with POST to users table...
-d '{"username":"yourName","password":"e8"}' https://api.parse.com/1/users
get the response from above request and parse the OID of the new user and the TOKEN value in the response. Persist them in your app to a durable 'user_prefs' type for future use with something like...
PreferenceManager.getDefaultSharedPreferences(myActivity).edit().put....
When you want to Write objects for that user do the following:
include in headers,
"X-Parse-Session-Token: pd..." // the token you saved
include ACL tag in json for POST of the parse class/object that you are writing...
the user OID within the ACL tag should be the OID value from the response when you created the new parse user
-H "X-Parse-Session-Token: pdqnd......." \
-d '{"ACL": {"$UserOID": {
"read": true,
"write": true
}}}' \
https://api.parse.com/1/classes/MyClass
READS:
Because the ACL for every object written to MyClass is exclusive to the user in '$UserOID, noone else can see them. As long as you include the token value in a header with any read, $UserOID will be the only one with access. The token value, originally returned when you created the new user is logically bound to the userOID and can be used in the header in kind of magic way... No server-session required on the device when the app starts, no explicit user authentication step required to the server, no query expression in a GET - simply provide the token value in the header layer and request all records(all users) it works to get records for just the userID inferred from the token value in the header. On init, the app just has to retrieve the token from 'shared_prefs' on the client side. Server side, the token lease is permanent.
-H "X-Parse-Session-Token: pdqnd......."
include above with every GET. -H "X-Parse-Session-Token: pdqnd......." You will be the only parse user who can see them...
if you want multiple devices bound to one parse user, this is NG.
if you want multiple parse accounts to be accessed from one instance of the app, this is NG.
You have to use relations. First, create a new column (not in your user's class) and the type is a relation, the relation is to the user class.
Lets say you want to add a new post. Use this:
ParseObject post = ...;
ParseUser user = ParseUser.getCurrentUser();
ParseRelation relation = user.getRelation("posts");
relation.add(yourString);
user.saveInBackground();
Code source
Tell me and I will edit this if you don't understand.
I guess you want something like for (to store some specific data for a particular parse user)
var note = new NoteOb();
note.set("text", text);
note.set("creator", currentUser);
note.setACL(new Parse.ACL(currentUser));
note.save(null, {
success:function(note) {
$("#newNoteText").val("");
getMyNotes();
}, error:function(note, error) {
//Should have something nice here...
}
});
And for: I want to fetch data from it
function getMyNotes() {
var query = new Parse.Query(NoteOb);
query.equalTo("creator", currentUser);
query.find({
success:function(notes) {
var s = "";
for(var i=0, len=notes.length; i<len; i++) {
s+= "<p>"+notes[i].get("text")+"</p>";
}
$("#currentNotes").html(s);
}
});
}
Check out this blog , it will give you a better understanding.