How do I paginate results from the Facebook SDK friends endpoint? - facebook

I'm using the Facebook SDK for JS to get a list of FB friends for a given FB user ID. Essentially, I make a request as follows:
FB.api(`/${fbUserId}/friends`, (response) => {
if (response && response.data) {
fbFriends = fbFriends.concat(response.data);
}
if (response && response.paging && response.paging.cursors && response.paging.cursors.after) {
// Recurse through.
}
});
I can get the first set of results, which contains 13 friends, and can also see that there are 200+ friends total, but the problem I'm having is when I try to recurse through and get all 200+ friends.
Specifically, I'm referencing the following two pages:
https://developers.facebook.com/docs/graph-api/using-graph-api/#cursors
https://developers.facebook.com/docs/graph-api/reference/user/friends/
Trying to put things together from those two pages, I thought that a request URL like the following would work:
const afterParam = response.paging.cursors.after ? `&after=${response.paging.cursors.after}` : '';
FB.api(`/${fbUserId}/friends${afterParam}`, (response) => {
...
But it doesn't return any results. I am console-logging response.paging.cursors.after, and I'm sure it's set appropriately from the first API call, but it's not returning any more friends. I always get back an empty array for response.data.
What am I doing wrong? Admittedly, the FB API docs seem a bit sparse, and I don't see anywhere where they specifically show how to go through pages of results for the friends API endpoint, but I'm obviously missing something. Thank you.

Related

Facebook Graph API - How to avoid request limits when accessing a user's photos?

I need to fetch user photos and albums using the Facebook Graph API.
As far as I understand (while reading the docs) this is a two step procedure, 1. fetching the id for each photo from the photos edge, 2. using the returned array of ids, fetching individual photo nodes.
Fetching individual photo nodes could mean hundreds of requests/s, while having a lot of photos on my profile I have hit the app request limits after a few minutes of testing.
Is there maybe a way to fetch all photos at once (or in fewer requests), in order to avoid request limits?
example implementation:
...
var photos = [];
function fetchPhotos(){
fetch('https://graph.facebook.com/v3.1/me/photos?type=uploaded&access_token=' + accesstoken, {
method: 'GET'
})
.then(photos => photos.json())
.catch(error => console.error('Error:', error))
.then(photos => {
this.fetchPhoto(photos);
});
}
function fetchPhoto(photos){
for(var i=0; i < photos.data.length; i++){
fetch('https://graph.facebook.com/v3.1/' + photos.data[i].id + '?fields=link,width,height&access_token=' + accesstoken, {
method: 'GET'
})
.then(photo => photo.json())
.catch(error => console.error('Error:', error))
.then(photo => {
photos.push(photo);
});
}
}
...
Thanks!
You can already get a list with all the fields with one call:
https://graph.facebook.com/v3.1/me/photos?fields=link,width,height&access_token=...
Side Note: If that is client code, why not use the official JS SDK? That way, you donĀ“t need to deal with the Access Token, it gets added automatically.

Not getting the name and other information of my friend who is also using the same app using facebook login

I am trying to fetch the information about my friends who are also logged in (or using) the app using facebook , for that i am using graph api . But i am not getting relevant information . Can anyone please help me out on that .
I went through the facebook developer docs and tried many option but it didn't helped .
//Request
FB.api(
"/{app-id}", // app-id for the application
{
"fields": "context.fields(friends_using_app)"
},
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
Using this when i am trying to fetch the information i am getting output like this
Not getting the name and other information of my friend who is also using the same app using facebook login .
This would be the correct code to get all friends who authorized the App too:
FB.api('/me/friends', (response) => {
if (response && !response.error) {
/* handle the result */
}
}

Get ALL Facebook posts using facebook api and paging

It's my intention to get all past posts. I have created a Facebook app. When this code is executed, I have properly logged in with the correct appid and secret.
function loadPage() { // calls the first batch of records
FB.api("/me/feed",{},function(response) { procBatch(response) } );
}
function procBatch(dat) { // handle this batch, request the next batch
for ( i = 0; i < dat.data.length; i++ ) {
procRow(dat.data[i]); // process this row
}
if ( typeof(dat.paging) != 'undefined' ) {
FB.api(dat.paging.next, {}, function(response){ procBatch(dat); } );
} else {
alert("No more records expected");
}
}
Unfortunately, this only takes me back about six months.
Is it possible to go back further?
Thanks in advance.
Yes, that's possible.
This can be done by increasing the limit of number object per page. I've not tried retrieving ALL the posts, but I am pretty sure that you can easily retrieve posts which are even few years old.
You can call /me/feed?limit=numberOfObjectsPerPage instead of just /me/feed to increase this limit.
You can find more information on this here. Do have a look at the Time Based Pagination on the link. This will explain you how to manage the output for the feeds.

How to get the post of the user using javascript sdk

I am creating my first facebook app using javascript sdk. In that i can able to post to the user's wall using(FB.api('me/feed', 'post', )).
Now what I need is, when the user accessing my app, it has to show (or list) the post of that user. The code is
FB.api('/me/posts', function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
alert('The value of post is:'+post);
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
But it is not working. If I remove l=response.length and change the condition as i<5 it is going inside the loop but it gives the value of post is undefined.
I didn't get why it is returning as undefined. It returns same for post.message also.
I am getting the access_token of the user also.
If I want to get the post of my user what code i have to use. Can anyone help me in this.
Thanks in advance
You can use the Facebook Graph API Explorer to better understand what data you will be receiving. https://developers.facebook.com/tools/explorer/
You should have l=response.data.length and var post = response.data[i];. Also, some posts will not have a "message", but will have a "story" instead (mainly posts like "Joe Smith and Tom Someone are now friends."). Make sure you also have the appropriate permissions (e.g. user_status) for the information you're trying to receive.

Facebook Graph API - Get ID from Facebook Page URL

I have seen this question but what I want is different.
I want to get the Facebook ID not from a general URL (and therefore conditional if it has Like button or not). I want to get the Facebook ID given a Facebook page using the Graph API.
Notice that Facebook pages can have several formats, such as:
http://www.facebook.com/my_page_name
http://www.facebook.com/pages/my_page_name
http://www.facebook.com/my_page_ID
I know I could do some regex to get either the my_page name or my_page_ID, but I am wondering if any one know if GraphAPI is supporting what I want.
It seems to me that the easiest solution to what you describe is to just get the id/name from the url you have using lastIndexOf("/") (which most languages have an equivalent for) and then get "https://graph.facebook.com/" + id.
The data that this url returns has the id (i.e.: 6708787004) and the username (i.e.: southpark), so regardless of which identifier you use (what you extract from the url using lastIndexOf), you should get the same result.
Edit
This code:
identifier = url.substring(url.lastIndexOf("/"))
graphUrl = "https://graph.facebook.com/" + identifier
urlJsonData = getGraphData(graphUrl)
Should work the same (that is result with the same data) for both:
url = http://www.facebook.com/southpark
And
url = http://www.facebook.com/6708787004
(you'll obviously need to implement the getGraphData method).
Also, the 2nd url form in the question is not a valid url for pages, at least not from my tests, I get:
You may have clicked an expired link or mistyped the address. Some web
addresses are case sensitive.
The answer to the question is posted above but the method shown below works fine we do not have to perform the regex on the facebook page urls
I got the answer by this method
FB.api('/any_fb_page_url', function(response){
console.log(response);
});
any_fb_page_url can be any of the following types
https://www.facebook.com/my_page_name
https://www.facebook.com/pages/my_page_name
https://www.facebook.com/my_page_ID
This are also listed in question above
This code is tested on JS console available on Facebook Developers site tools
You can get the page id by using the below api
https://graph.facebook.com/v2.7/smhackapp?fields=id,name,fan_count,picture,is_verified&access_token=access_token&format=json
Reference image
This answer is updated and checked in 2019:
and it is very simple because you do not need to extract anything from the link. for examples:
https://www.facebook.com/pg/Vaireo-Shop-2138395226250622/about/
https://www.facebook.com/withminta
https://www.facebook.com/2138395226250622
https://graph.facebook.com/?id=link&access_token=xxxxxxxx
response:
{
"name": "Vaireo Shop",
"id": "2138395226250622"
}
full nodeJS answer:
async function getBusinessFromFBByPageURL(pageURL: string) {
const accessToken = process.env.fb_app_access_token;
const graphUrl = `https://graph.facebook.com/?id=${pageURL}? access_token=${accessToken}`;
const fbGraphResponse = await Axios.get(graphUrl);
<?php
function getFacebookId($url) {
$id = substr(strrchr($url,'/'),1);
$json = file_get_contents('http://graph.facebook.com/'.$id);
$json = json_decode($json);
return $json->id;
}
echo getFacebookId($_GET['url']);
?>
Thats a PHP example of how to get the ID.
As of Nov 26 2021 none of these solutions work.
Facebook has locked down the API so you need an App Review.
https://developers.facebook.com/docs/pages/overview/permissions-features#features
This answer takes into account that a URL can end with a trailing slash, something that Facebook event pages seem to have in their URLs now.
function getId(url) {
var path = new URL(url).pathname;
var parts = path.split('/');
parts = parts.filter(function(part) {
return part.length !== 0;
});
return parts[parts.length - 1];
}
You can Use Requests and re Modules in python
Code:
import requests,re
profile_url = "https://www.facebook.com/alanwalker97"
idre = re.complie('"entity_id":"([0-9]+)"')
con = requests.get(profile_url).content
id = idre.findall(con)
print("\n[*] ID: "+id[0])
Output:
[*] ID: 100001013078780
Perhaps you can look through the https://developers.facebook.com/docs/reference/api/#searching docs: search against a couple of types and if you find what you're looking for go from there.