Facebook Graph API - Get ID from Facebook Page URL - facebook

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.

Related

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.

Post on Friends' Wall(s) via Facebook Actionscript 3 SDK

I'm absolutely new to programming and just managed to learn the basics of ActionScript 3. Now, I would like to learn how to post on my Friends' Walls via the as3 SDK using the UI class (taken from a nice Tutorial):
This is how I post on my own Wall:
protected function newsFeed ():void
{
// define your caption text
var theCaption:String = "CaptionText";
// define the descrition text
var theDescription:String = "Text for game Achievement";
// We need to follow the FB docs to tell it what sort of input we are sending to FB
// We are trying to set the 'feed'
var methodInput:String = 'feed';
var thePicture:String = "mylink/picture.png";
var theLink:String = "mylink";
var theName:String = "Name of FB Status Setter";
// Create an object that we'll call 'data' and fill it with the actual data we're sending to Facebook
var data:Object = {
caption:theCaption,
description:theDescription,
picture:thePicture,
name:theName,
link:theLink
};
Facebook.ui(methodInput, data, onUICallback);
}
protected function onUICallback(result:Object):void
{
// do something
}
This works perfectly fine. I know that I have to integrate the parameter "to" somewhere. But I don't know where and how. Sorry I'm very very new to this. This is from Facebook Docs
Properties
from: The ID or username of the user posting the message. If this is unspecified, it defaults to the current user. If specified, it must be the ID of the user or of a page >that the user administers.
to: The ID or username of the profile that this story will be published to. If this >is unspecified, it defaults to the the value of from.
Hopefully someone can help me out.
Best Regards,
Amir
P.S.: Is there a way to post only one friend's wall and another way to post on several friends' walls?
I believe you want to use Facebook.api() rather than 'ui'. According to the documentation for the AS3 FB API, 'ui' just opens the share dialog. If you want to create a post on a friends wall, then you'll want to use 'api'.
I haven't tested this in Flash, but I think you can set the method as /PROFILE_ID/feed ... of course replacing "PROFILE_ID" with the FB uid of the friend. Then, include the arguments; message, picture, link, name, caption, description and source in your data object.
So your code would look something like:
var method:String = "/friend_id/feed";
var data:Object = {};
data.message = "Your message";
data.picture = "http://www.google.com/kittens.jpg";
data.link = "http://www.mysite.com/link";
data.caption = "Your caption";
data.description = "Your description";
data.source = "http://www.mysite.com/video.swf";//(optional) source is a video or Flash SWF
Facebook.api(method, yourCallback, data, "POST");
function yourCallback(result:Object, fail:Object):void {
if (result) {
trace(result)
} else if (fail) {
trace(fail);
}
}
If you have multiple friends, you could probably just put the uid's in an array and loop through the method above. The AS3 API has a batch request method that I haven't tried, but you can check out the Documentation.
Facebook has some pretty helpful tools that are somewhat hidden.
Checkout their Debugger and their Graph API Explorer
Hope that's helpful.

Can't send a link to my own wall

I am developing a multi protocol client (currently Twitter, Facebook and Google Reader) for Windows using C# and wanted to extend its functions to send links to Facebook (currently I "only" have text status messages, comments and likes).
So I wrote this quite small method here:
public void PostLink(string text, string url)
{
if (string.IsNullOrEmpty(url))
{
PostTextStatus(text);
return;
}
dynamic parameters = new ExpandoObject();
parameters.message = text;
parameters.link = System.Web.HttpUtility.UrlEncode(url);
dynamic result = facebookClient.Post("me/links", parameters);
UpdateNewsFeed();
}
But I get the following error message back from Facebook: "(OAuthException) (#1500) The url you supplied is invalid"
But at least as I read the API docs this should be the right url and I tried it also with my user ID instead of "me" and without the UrlEncode - no luck so far.
Any help appreciated :)
(Using latest stable version für Facebook C# SDK)
The used client is initiated by
facebookClient = new FacebookClient(AccessToken);
dynamic result = (IDictionary<string, object>)facebookClient.Get("me");
if (result != null)
{
LoginSuccessfull = true;
}
}
and the AccesToken and its permissions were retrieved using
IDictionary<string, object> loginParameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "appId", appId},
{ "secret", appSecret }
};
Uri redirectUri = new Uri("http://www.li-ghun.de/Nymphicus/");
loginUri = FacebookOAuthClient.GetLoginUrl(appId, null, _extendedPermissions, loginParameters);
with I think quite more than enough permissons:
private string[] _extendedPermissions = new[] {
"user_activities",
"user_birthday",
"user_checkins",
"user_education_history",
"user_events",
"user_games_activity",
"user_groups",
"user_hometown",
"user_interests",
"user_likes",
"user_location",
"user_notes",
"user_online_presence",
"user_photo_video_tags",
"user_photos",
"user_questions",
"user_relationship_details",
"user_relationships",
"user_religion_politics",
"user_status",
"user_subscriptions",
"user_videos",
"user_website",
"user_work_history",
"friends_about_me",
"friends_activities",
"friends_birthday",
"friends_checkins",
"friends_education_history",
"friends_events",
"friends_games_activity",
"friends_groups",
"friends_hometown",
"friends_interests",
"friends_likes",
"friends_location",
"friends_notes",
"friends_online_presence",
"friends_photo_video_tags",
"friends_photos",
"friends_questions",
"friends_relationship_details",
"friends_relationships",
"friends_religion_politics",
"friends_status",
"friends_subscriptions",
"friends_videos",
"friends_website",
"friends_work_history",
"create_event",
"create_note",
"email",
"export_stream",
"manage_friendlists",
"manage_notifications",
"manage_pages",
"offline_access",
"photo_upload",
"publish_actions",
"publish_checkins",
"publish_stream",
"read_friendlists",
"read_insights",
"read_mailbox",
"read_requests",
"read_stream",
"rsvp_event",
"share_item",
"status_update",
"video_upload",
};
Problem has been all the time at myself being stupid - I accidently exchanged the parameters when calling my method so the text of the entry was in the link property and vica versa.
Stupid me :(
I think your issue lies in the URL being posted as the link. Be sure that URL is visible to the linter (https://developers.facebook.com/tools/lint).
Another thing is to try playing with the Graph API Explorer tool and see if you can use it to post a link. If so, then try changing the application drop down to the app you're having issues with and try posting the link again.
In my case i was posting "http://localhost:3000" and facebook reject it. I tried with "www.google.com" and it works
The error I was getting was, even though the URL itself was valid, the og:image was being set to //example.com/example.jpg and missing http: or https:. I blame Facebook for this one, for not accepting a valid URL that any browser will accept, but the Debugger definitely helped identify this and solved the issue.
https://developers.facebook.com/tools/lint

Using Facebook Requests 2.0 with the C# SDK

I am trying to update the bookmark count field with the SDK but have not had any success yet.
Can somebody tell me what classes I need to instantiate to do something similar to the following link:
http://developers.facebook.com/blog/post/464
Note:
The link demonstrates how to set the bookmark count and delete it. I would like to be able to do the same with the SDK, any help would be appreciated.
To do this, first you need to get you app's access token:
private string GetAppAccessToken() {
var fbSettings = FacebookWebContext.Current.Settings;
var accessTokenUrl = String.Format("{0}oauth/access_token?client_id={1}&client_secret={2}&grant_type=client_credentials",
"https://graph.facebook.com/", fbSettings.AppId, fbSettings.AppSecret);
// the response is in the form: access_token=foo
var accessTokenKeyValue = HttpHelpers.HttpGetRequest(accessTokenUrl);
return accessTokenKeyValue.Split('=')[1];
}
A couple of things to note about the method above:
I'm using the .Net HttpWebRequest instead of the Facebook C# SDK to grab the app access_token because (as of version 5.011 RC1) the SDK throws a SerializationException. It seems that the SDK is expecting a JSON response from Facebook, but Facebook returns the access token in the form: access_token=some_value (which is not valid JSON).
HttpHelpers.HttpGetRequest simply uses .Net's HttpWebRequest. You can just as well use WebClient, but whatever you choose, you ultimately want to make this http request:
GET https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials HTTP/1.1
Host: graph.facebook.com
Now that you have a method to retrieve the app access_token, you can generate an app request as follows (here I use the Facebook C# SDK):
public string GenerateAppRequest(string fbUserId) {
var appAccessToken = GetAppAccessToken();
var client = new FacebookClient(appAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Test: Action is required";
parameters.data = "Custom Data Here";
string id = client.Post(String.Format("{0}/apprequests", fbUserId), parameters);
return id;
}
Similarly, you can retrieve all of a user's app requests as follows:
Note: you probably don't want to return "dynamic", but I used it here for simplicity.
public dynamic GetAppRequests(string fbUserId) {
var appAccessToken = GetAppAccessToken();
var client = new FacebookClient(appAccessToken);
dynamic result = client.Get(String.Format("{0}/apprequests", fbUserId));
return result;
}
I hope this helps.

How to construct a REST API that takes an array of id's for the resources

I am building a REST API for my project. The API for getting a given user's INFO is:
api.com/users/[USER-ID]
I would like to also allow the client to pass in a list of user IDs. How can I construct the API so that it is RESTful and takes in a list of user ID's?
If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.
RESTful attempt:
POST http://example.com/api/batchtask
[
{
method : "GET",
headers : [..],
url : "/users/id1"
},
{
method : "GET",
headers : [..],
url : "/users/id2"
}
]
Server will reply URI of newly created batchtask resource.
201 Created
Location: "http://example.com/api/batchtask/1254"
Now client can fetch batch response or task progress by polling
GET http://example.com/api/batchtask/1254
This is how others attempted to solve this issue:
Google Drive
Facebook
Microsoft
Subbu Allamaraju
I find another way of doing the same thing by using #PathParam. Here is the code sample.
#GET
#Path("data/xml/{Ids}")
#Produces("application/xml")
public Object getData(#PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...
There seems to be a few ways to achieve this. I'd like to offer how I solve it:
GET /users/<id>[,id,...]
It does have limitation on the amount of ids that can be specified because of URI-length limits - which I find a good thing as to avoid abuse of the endpoint.
I prefer to use path parameters for IDs and keep querystring params dedicated to filters. It maintains RESTful-ness by ensuring the document responding at the URI can still be considered a resource and could still be cached (although there are some hoops to jump to cache it effectively).
I'm interested in comments in my hunt for the ideal solution to this form :)
You can build a Rest API or a restful project using ASP.NET MVC and return data as a JSON.
An example controller function would be:
public JsonpResult GetUsers(string userIds)
{
var values = JsonConvert.DeserializeObject<List<int>>(userIds);
var users = _userRepository.GetAllUsersByIds(userIds);
var collection = users.Select(user => new { id = user.Id, fullname = user.FirstName +" "+ user.LastName });
var result = new { users = collection };
return this.Jsonp(result);
}
public IQueryable<User> GetAllUsersByIds(List<int> ids)
{
return _db.Users.Where(c=> ids.Contains(c.Id));
}
Then you just call the GetUsers function via a regular AJAX function supplying the array of Ids(in this case I am using jQuery stringify to send the array as string and dematerialize it back in the controller but you can just send the array of ints and receive it as an array of int's in the controller). I've build an entire Restful API using ASP.NET MVC that returns the data as cross domain json and that can be used from any app. That of course if you can use ASP.NET MVC.
function GetUsers()
{
var link = '<%= ResolveUrl("~")%>users?callback=?';
var userIds = [];
$('#multiselect :selected').each(function (i, selected) {
userIds[i] = $(selected).val();
});
$.ajax({
url: link,
traditional: true,
data: { 'userIds': JSON.stringify(userIds) },
dataType: "jsonp",
jsonpCallback: "refreshUsers"
});
}