Facebook InsightsAPI calls limited to 25 entries - facebook

I'm pretty new to programming and I'm currently trying to use the InsightsAPI of Facebook in order to extract our performance data. The problem is that the response of the API call is limited to 25 entries.
I use the following code for the call:
String access_token = "xxx";
String ad_account_id = "yyy";
setApp_secret("zzz");
APIContext context = new APIContext(access_token).enableDebug(false);
APINodeList<AdsInsights> response = new AdAccount(ad_account_id, context).getInsights()
.setLevel(AdsInsights.EnumLevel.VALUE_CAMPAIGN)
.setBreakdowns(Arrays.asList(AdsInsights.EnumBreakdowns.VALUE_COUNTRY))
.setTimeRange("{\"since\":\"2017-09-01\",\"until\":\"2017-09-30\"}")
.requestField("account_id")
.requestField("campaign_id")
.requestField("impressions")
.requestField("clicks")
.execute();
How can I extend the limit of the response? I found some information about how to do this via curl but there were no hints on how to do this with java. Would be great if anyone of you could help me!
All the best,
Paul

All the responses of Graph API are paginated which means you will get at most 'x' number of results where 'x' is 25 by default at the moment.
You can specify a higher value using limit param but it is not recommended as it is likely to cause a timeout.
You should look into using pagination instead: https://developers.facebook.com/docs/graph-api/using-graph-api/#paging

Related

Get follower count on Scratch (API)

I am looking to find the follower count of a Scratch user using the Scratch API. I already know how to get their message count, with https://api.scratch.mit.edu/users/[USER]/messages/count/.
This answer targets the Scratch REST API, documented here.
You get the user's followers by requesting them: https://api.scratch.mit.edu/users/some_username/following where some_username is to be replaced by the actual username.
This will return 0 to 20 results (20 is the default limit of objects returned by the REST API). If there's less than 20 results, then you're done. The amount of followers is simply the count of the objects returned.
If there's 20 objects returned, we can't be certain we've requested all the user's friends as there might be more to come. Therefore, we skip the first 20 followers of that user by supplying the ?offset= parameter: https://api.scratch.mit.edu/users/some_username/following?offset=20
This retrieves the second 'page' of friends. Now we simply loop through the procedure described above, incrementing offset by 20 each time until either less than 20 results are returned or no results are returned. The amount of friends of that user is the cumulative count of the objects returned.
As mentioned by _nix on this forum thread, there is currently no API to achieve this. However, he/she rightly points out that the number can be obtained from a user's profile page.
You may write a script (in JavaScript, for example) to parse the HTML and get the follower count in the brackets at the top of the page.
Hope this helps!
There is a solution in Python:
import requests
import re
def followers(self,user):
followers = int(re.search(r'Followers \(([0-9]+)\)', requests.get(f'https://scratch.mit.edu/users/{user}/followers').text, re.I).group(1))
return f'{followers} on [scratch](https://scratch.mit.edu/users/{user}/followers)'
Credit goes to 12944qwerty, in his code (adapted to remove some implementation specific stuff).
use ScratchDB
var user = "username here";
fetch(`https://scratchdb.lefty.one/v3/user/info/${user}`).then(res => res.json()).then(data => {
console.log(`${user} has ` + data["followers"].toString() + " followers");
}
(Edit: this is javascript btw, I prefer Python but Python doesn't have a cloud.set function and this is how I did it)
Use ScratchDB (I used httpx, but you can GET with anything):
import httpx
import json
user = "griffpatch"
response = httpx.get(f"https://scratchdb.lefty.one/v3/user/info/{ user }")
userData = json.loads(response.text)
followers = userData["statistics"]["followers"]
https://api.scratch.mit.edu/users/griffpatch/followers
this gives the follower names, scratch staus(scratch team or not), pfp, everything in their profile

How to fix 400 Bad Request with empty filter query in RestHeart?

I am using Restheart and MongoDB. And I am calling one service(API) for the response data.
Working API
http://127.0.0.1:8080/test/donor?filter="{'name':'john'}"
When I calling above API then it is working, But When I putted API filter is empty, Like filter={} then it is not working.
Not Working API
http://127.0.0.1:8080/test/donor?filter="{}"
When I calling API with empty filter="{}", Then its giving me 400 Bad Request
Actually I wan to achieve one API Call for two purpose.
One for with filter condition.
Second one without filter condition.
I want to call Like below.
var qryFilter = {};
var qryFilterParam;
qryFilter["color.code"] = dateInParameter.code;
qryFilterParam = '&filter=' + JSON.stringify(qryFilter)
http://127.0.0.1:8080/test/donor?qryFilterParam
Then some time qryFilterParam have value and some time don't have. When Its have values like filter="{'name':'john'}" then it is working but when it's don't have key value like filter="{}" then it is not working. I am searching solution on website http://restheart.org/curies/1.0/filter.html but I am not able find to solution.
An empty filter is not allowed by restheart.
You need an if statement in your code to make a request with filter qparam and a request without.

Why does one HTTP GET request retrieve the required data and another retrieve []

I'm currently working on ng-admin.
I'm having a problem retrieving user data from my REST API (connected to a MongoDB) and displaying it.
I have identified the problem as the following:
When I enter http://localhost:3000/users into my browser, I get a list of all users in my database.
When I enter http://localhost:3000/users?_page=1&_perPage=30&_sortDir=DESC&_sortField=id,
I get [] as a result.
I am quite new to this, I used both my browser and the POSTMAN Chrome extension to test this and get the same result.
http://localhost:3000/users_end=30&_order=DESC&_sort=id&_start=0
This (/users_end) is a different request than /users.
It should be:
http://localhost:3000/users?end=30&_order=DESC&_sort=id&_start=0
Or, by looking at the other parameters:
http://localhost:3000/users?_end=30&_order=DESC&_sort=id&_start=0
with end or _end being the first parameter (mark the ?).
Update (it is ? and before the _, I have edited.):
If adding parameters to the request returns an empty list, try adding only one at a time to narrow down the problem (there's probably an error in the usage of those parameters - are you sure you need those underscores?).
Your REST API must have a way to handle pagination, sorting, and filtering. But ng-admin cannot determine exactly how, because REST is a style and not a standard. So ng-admin makes assumptions about how your API does that by default, that's why it adds these _end and _sort query parameters.
In order to transform these parameters into those that your API understands, you'll have to add an interceptor. This is all thoroughly explained in the ng-admin documentation: http://ng-admin-book.marmelab.com/doc/API-mapping.html

Linkedin API oAuth 2.0 REST Query parameters

I'm running into a problem with adding a query to the callback URL. I'm getting an invalid URI scheme error attempting to authorize the following string:
https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=75df1ocpxohk88&scope=rw_groups%20w_messages%20r_basicprofile%20r_contactinfo%20r_network&state=7a6c697d357e4921aeb1ba3793d7af5a&redirect_uri=http://marktest.clubexpress.com/basic_modules/club_admin/website/auth_callback.aspx?type=linkedin
I've read some conflicting information in forum posts here. Some say that it's possible to add query strings to callbacks, and others say that it results in error.
If I remove ?type=linkedin, I can authorize just fine and receive the token. It would make my life so much easier if I could use a query string on the callback url, as I need to do some additional processing in the callback.
In short, can I append a query string to the end of the callback url?
For fun, I tried encoding the callback url in the request (obviously this is a no-no according to their documentation):
https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=75df1ocpxohk88&scope=rw_groups%20w_messages%20r_basicprofile%20r_contactinfo%20r_network&state=5cabef71d89149d48df523558bd12121&redirect_uri=http%3a%2f%2fmarktest.clubexpress.com%2fbasic_modules%2fclub_admin%2fwebsite%2fauth_callback.aspx%3ftype%3dlinkedin
This also resulted in an error but was worth a shot.
The documetation here: https://developer.linkedin.com/forum/oauth-20-redirect-url-faq-invalid-redirecturi-error indicates that you CAN use query parameters. And in the first request, it appears that I'm doing it correctly. Post #25 on this page - https://developer.linkedin.com/forum/error-while-getting-access-token indicates that you have to remove the query parameters to make it work
Anyone have experience with successfully passing additional query paramaters in the callback url for the linkedin API using oAuth2.0? If so, what am I doing wrong?
I couldn't wait around for the Linkedin rep's to respond. After much experimentation, I can only surmise that the use of additional query parameters in the callback is not allowed (thanks for making my application more complicated). As it's been suggested in post #25 from the question, I've tucked away the things I need in the "state=" parameter of the request so that it's returned to my callback.
In my situation, I'm processing multiple API's from my callback and requests from multiple users, so I need to know the type and user number. As a solution, I'm attaching a random string to a prefix, so that I can extract the query parameter in my callback and process it. Each state= will therefore be unique as well as giving me a unique key to cache/get object from cache..
so state="Linkedin-5hnx5322d3-543"
so, on my callback page (for you c# folks)
_stateString=Request["state"];
_receivedUserId = _stateString.Split('-')[2];
_receivedCacheKeyPrefix = _stateString.Split('-')[0];
if(_receivedCacheKeyPrefix == "Linkedin") {
getUserDomain(_receivedUserId);
oLinkedIn.AccessTOkenGet(Request["code"],_userDomain);
if (oLinkedin.Token.Length > 0) {
_linkedinToken = oLinkedin.Token;
//now cache token using the entire _statestring and user id (removed for brevity)
}
You not allowed to do that.
Refer to the doc: https://developer.linkedin.com/docs/oauth2
Please note that:
We strongly recommend using HTTPS whenever possible
URLs must be absolute (e.g. "https://example.com/auth/callback", not "/auth/callback")
URL arguments are ignored (i.e. https://example.com/?id=1 is the same as https://example.com/)
URLs cannot include #'s (i.e. "https://example.com/auth/callback#linkedin" is invalid)

The definitive guide to posting a Facebook Feed item using pure C#

Does anyone have a definitive way to post to a user's wall, using nothing but the .NET Framework, or Silverlight?
Problems deriving from people's attempts have been asked here on SO, but I cannot find a full, clear explanation of the Graph API spec and a simple example using WebClient or some similar class from System.Net.
Do I have to send all feed item properties as parameters in the query string? Can I construct a JSON object to represent the feed item and send that (with the access token as the only parameter)?
I expect its no more than a 5 line code snippet, else, point me at the spec in the FB docs.
Thanks for your help,
Luke
This is taken from how we post to a user's wall. We place the data for the post in the request body (I think we found this to be more reliable than including all the parameters in the query part of the request), it has the same format as a URL encoded query string.
I agree that the documentation is rather poor at explaining how to interact with a lot of resources. Typically I look at the documentation for information on fields and connections, then work with the Graph API Explorer to understand how the request needs to be constructed. Once I've got that down it's pretty easy to implement in C# or whatever. The only SDK I use is Facebook's Javascript SDK. I've found the others (especially 3rd party) are more complicated, buggy, or broken than rolling my own.
private void PostStatus (string accessToken, string userId)
{
UriBuilder address = new UriBuilder ();
address.Scheme = "https";
address.Host = "graph.facebook.com";
address.Path = userId + "/feed";
address.Query = "access_token=" + accessToken;
StringBuilder data = new StringBuilder ();
data.Append ("caption=" + HttpUtility.UrlEncodeUnicode ("Set by app to describe the app."));
data.Append ("&link=" + HttpUtility.UrlEncodeUnicode ("http://example.com/some_resource_to_go_to_when_clicked"));
data.Append ("&description=" + HttpUtility.UrlEncodeUnicode ("Message set by user."));
data.Append ("&name=" + HttpUtility.UrlEncodeUnicode ("App. name"));
data.Append ("&picture=" + HttpUtility.UrlEncodeUnicode ("http://example.com/image.jpg"));
WebClient client = new WebClient ();
string response = client.UploadString (address.ToString (), data.ToString ());
}
I don't know much about .net or silverlight, but the facebook api works with simple http requests.
All the different sdks (with the exception of the javascript one) are mainly just wrappers for the http requests with the "feature" of adding the access token to all requests.
Not in all requests the parameters are sent as querystring, in some POST requests you need to send them in the request body (application/x-www-form-urlencoded), and you can not send the data as json.
If the C# sdk is not to your liking, you can simply create one for your exact needs.
As I wrote, you just need to wrap the requests, and you can of course have a method that will get a json as parameter and will break it to the different parameters to be sent along with the request.
I would point you to the facebook documentation but you haven't asked anything specific so there's nothing to point you to except for the landing page.