Essential Graph API of Facebook

essential facebook graphFacebook recently updated their platform and added some new graph APIs. In this tutorial I’ll show some important usage of graph api. The examples here I provided as a cook-book format.

If you’re beginner then please read my previous articles:

1. Get total number of  Share of an url

If you integrated facebook share for your site or if any person share your site url (any url) in facebook then facebook will automatically create an open graph object and tracked the number of users who is sharing that via facebook.  Just use below code to know the number of share

       $pagelike = '';
        try {
            $pagelike = $facebook->api("/$urllike");
        }
        catch(Exception $o) {
            print_r($o);
        }
        echo '<pre>';
        print_r($pagelike);
        echo '</pre>';

For example if I provided http://thinkdiff.net as $urllike it will output

Array
(
    [id] =>http://thinkdiff.net
    [shares] => 628
)

2. Get brief information of a facebook page

If you have a facebook fan page and wants to know  summary of the page you can use

       $fbpageinfo =   '';
        try {
            $fbpageinfo = $facebook->api("/YOURFANPAGE_ID_OR_NAME");
        }
        catch(Exception $o) {
             print_r($o);
        }
        echo '<pre>';
      print_r($fbpageinfo);
       echo '</pre>';

For example I’ve a fan page that’s title is thinkdiff.net so I just used

$fbpageinfo = $facebook->api("/thinkdiff.net");

It outputs

Array
(
    [id] => 314110374728
    [name] => Thinkdiff.net
    [picture] => http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs338.snc4/41817_314110374728_5766_s.jpg
    [link] => http://www.facebook.com/thinkdiff.net
    [category] => Local_technology_telecommunications_services
    [website] => http://thinkdiff.net

http://thinkbd.net


http://ftechdb.com

    [fan_count] => 1524
    ......... AND MORE.......
)

Facebook Page API Details

3. Publish something that contains link, photo to a facebook page

This solution is very helpful if you want to publish automatically something in a facebook fan page via your application.

//publish in fanpage
        if (isset($_REQUEST['publish'])){
            try {
                  $wallpostpage = $facebook->api('/FACEBOOK_FAN_PAGE_ID_OR_NAME/feed', 'post',
                                  array(
                                      'message' => 'I like iThinkdiff.net',
                                      'picture' => 'http://thinkdiff.net/ithinkdiff.png',
                                      'link'    => 'http://ithinkdiff.net',
                                      'name'    => 'iThinkdiff.net',
                                      'cb'      => ''
                                      )
                                  );
            } catch (FacebookApiException $e) {
                 print_r($o);
            }
        }

Just change the parameters and the FACEBOOK_FAN_PAGE_ID_OR_NAME

For example I just posted using my application.

$facebook->api('/thinkdiff.net/feed', 'post', array(......));

Facebook Post API Details

4. Upload photos in your profile or any particular album that you own

Please keep in mind that you could only upload photos in your profile or your albums via application.  A typical scenario of this would be, you’ve a website where people are logged in via facebook connect. In that site there are many photos and your user may wants to upload some of photos in his facebook album.

When you’ll create $facebook object then set ‘fileupload’ => true

 $facebook = new Facebook(array(
      'appId'  => $fbconfig['appid'],
      'secret' => $fbconfig['secret'],
      'cookie' => true,
      'fileUpload' => true
    ));

Use below code, if you provide album id then the photo will be uploading in corresponding album otherwise the application will create an album and will upload photos on that. Please remember, ‘source’ should be absolute file path not be any url. And you must have to provide the ‘@’ symbol before filename. Suppose your php code is in /var/www/ folder and the image file is also in /var/www/ folder. Then just use source => ‘@filename.jpg’

$albumID    =   isset($_REQUEST['albumid']) ? $_REQUEST['albumid'] :  'me';

try {
    $uploadstatus = $facebook->api("/$albumID/photos", 'post',
            array(
            'source'  =>  '@FILENAME',
            'message' => 'Messsage'
            )
    );
} catch (FacebookApiException $e) {
    print_r($o);
}

Facebook Photo API Details

5. Read comments/like of a post or photo

Every post or photo or album has an id, so using that id you can easily retrieve data. Suppose you want to retrieve recently your tagged photos. Then you can do so…

       try {
            $photos = $facebook->api("/me/photos");
        }
        catch(Exception $o) {
           print_r($o);
        }
        echo '<pre>';
       print_r($photos);
       echo '</pre>';

You’ll see recently your tagged photos. Now In the output you’ll see each photo has an ‘id’, so if you want to read comments of that id just use

       try {
            $photo = $facebook->api("/PHOTO_ID_OR_ALBUM_ID_OR_POST_ID");
        }
        catch(Exception $o) {
             print_r($o);
        }
        echo '<pre>';
       print_r($photo);
       echo '</pre>';

6. Create events via php using facebook API

This is super easy. Suppose in your website you want your user may create events then using below code you can do so

try {
    $event = $facebook->api("/me/events", 'post',
            array(
            'name'       => 'Facebook Users Party',
            'start_time' => '1272718027',
            'end_time'   => '1272718027'

                )
    );
} catch (FacebookApiException $e) {
    print_r($o);
}

Where start_time and end_time would be A JSON string containing an ISO-8601 formatted date/time.

Facebook Event API Details

7. Get total number of like of an URL

If you want to know the total numbers of people who like an URL, you can easily do that the following way. Just use php curl to get the xml output


http://api.facebook.com/restserver.php?method=links.getStats&urls=URL

For example if i just browse


http://api.facebook.com/restserver.php?method=links.getStats&urls=http://thinkdiff.net/facebook/essential-graph-api-of-facebook/

It outputs

<links_getStats_response xsi:schemaLocation="http://api.facebook.com/1.0/ http://api.facebook.com/1.0/facebook.xsd" list="true">
−
<link_stat>
−
<url>

http://thinkdiff.net/facebook/essential-graph-api-of-facebook/

</url>
<share_count>6</share_count>
<like_count>21</like_count>
<comment_count>0</comment_count>
<total_count>27</total_count>
<click_count>0</click_count>
−
<normalized_url>

http://www.thinkdiff.net/facebook/essential-graph-api-of-facebook/

</normalized_url>
</link_stat>
</links_getStats_response>

There are many more API descriptions in facebook documention. Like video, user, note, message, group. So just visit facebook documentation and read their API descriptions to complete your requirements.

:)

About mahmud ahsan

Programming is my passion from high school. I always looking for innovating new ideas and making them real application. I love mobile application and game development as well as web development. Having 4+ years web development experience and 6+ years mobile application development experience on different platform and business on it. My Mobile Apps Portfolio: iThinkdiff.net Mobile Apps

, ,

58 Responses to Essential Graph API of Facebook

  1. Danil K. November 29, 2010 at 5:15 pm #

    Informative and useful, as always. Thanks!

  2. ccarrasco November 29, 2010 at 7:05 pm #

    amazing article, thanks :)

  3. Avedis November 29, 2010 at 7:32 pm #

    Awesome!… just in time! :D

  4. jasmine December 1, 2010 at 3:04 pm #

    What is the difference between form processing in ie and other browsers?
    Why aftre clicking the fb:serverFbml there is somting like this in ie:
    http://apps.facebook.com/xxx/xxx.php/?s … cbc4%22%7D
    Why there isnt this session in other browsers?
    Thanks.

  5. Breklin December 3, 2010 at 2:43 am #

    I am trying to prepare a report for promotions we are going to be running in tab on our page to get the userid’s and date of likes…any input on this? I can’t seem to find a viable solution anywhere.

  6. Azzam December 7, 2010 at 4:30 pm #

    Hi Mahmud,

    I notice that sometimes I share a wordpress post via the like button amongst my friends but that has also been shared by other people ie. on a fanpage. A lot of great discussions goes on but all of these comments are scattered since different people sharing amongst their own friends.
    Q? Is it possible outside of facebook, especially on the original blog post to collate all of those comments?

    Or at the least if the post is shared via a custom custom facebook app [sort of integrates the like button] then maybe those comments can be collected?

    Azzam

  7. Marco December 16, 2010 at 1:03 pm #

    Hi Mahmud, i created a new app and set extended permissions for user_relationship_details which gives me the significant other of the user. I need to be able to get the user’s wife or husband or boyfriend, grilfriend in case the user has one. Even though i set this permissions, once the user authorizes the application, i can’t get the significant_other id, if i do this
    https://graph.facebook.com/me
    I just get the basic info but not the extendend permissions. I even got the access_token and send it as parameter and still can’t get that additional info. I hope you can help me with this problem since i’ve been looking all over the web and haven’t found an answer. I even tried fql to no avail.

    Thanks for your help

    • mahmud ahsan December 16, 2010 at 10:19 pm #

      According to http://developers.facebook.com/docs/authentication/permissions , user_relationships permission is required to get relationship info about your users. As you said you’re not fully success to get info then additionally you could pass “friends_relationships” permission and lets check what happens.

      • Jignesh Sura January 7, 2011 at 1:13 pm #

        Hi Mahumad,

        I tried to see the whole response object of User API to check whether significant_other data is being pulled or not and it seems like it doesnt pulls that data. The only data that it pulls is the one that is listed on the link given above on the USER object page. I dont know whether its a bug and should be reported or if i am doing it incorrectly then please let me know how to solve this issue.

        I have all the extended permissions possible to get relationship data from user

        Seems like my above comment was in wrong location, This reply is related to comment on significant_user post

  8. Boon December 17, 2010 at 5:09 am #

    Hi Mahmud, great sample and tutorial.

    I want to ask if this works with the migrations on Facebook?

    “If you currently use the fb_sig parameters, you can continue using them for the foreseeable future, but you won’t get new features nor will the documentation indicate how to use fb_sig. If you can, we recommend moving to signed_request.

    “Canvas Session Parameter” has been superseded by “OAuth 2.0 for Canvas”.”

    Thank you Mahmud. =)

    • mahmud ahsan December 17, 2010 at 11:48 am #

      If you migrated then you’ll no longer get the session parameters fb_sig_** . But using new sdk you also don’t need those session parameters.

  9. Qasim Ikram December 21, 2010 at 11:53 pm #

    Can you tell how can i get friends List for a user using GRAPH API…… small code will be very helpfull……Thanx

    • mahmud ahsan December 22, 2010 at 12:27 pm #

      $facebook->api(‘/USERID/friends’); using php sdk

  10. wasi January 6, 2011 at 12:23 pm #

    please help me. i want to publish on user wall on facebook page tab using facebook api.

    thanks

  11. bob January 6, 2011 at 9:42 pm #

    Hi Mahmud, great tutorial, very useful, thanks

  12. szenma January 19, 2011 at 6:00 pm #

    please help me i am troubled with this code

    include’facebook1/src/facebook.php';

    $app_id = “76abd6c860294319cf8062d9457591e”;
    $app_secret = “f445b607085105e6328d806dde80629″;

    $facebook = new Facebook(array(
    ‘appId’ => $app_id,
    ‘secret’ => $app_secret,
    ‘cookie’ => true
    ));

    if(is_null($facebook->getUser()))
    {
    header(“Location:{$facebook->getLoginUrl(array(‘req_perms’ => ‘user_status,publish_stream,user_photos’))}”);
    //exit;
    }
    //$tok=$facebook->getAccessToken();
    include “../admin/control/db_connection.php”;
    $query = “SELECT * FROM `image_dis` where im_subsub=’Krishna'”;
    $result = mysql_query($query, $db) or die(mysql_error($db));
    while($row=mysql_fetch_object($result)){

    // $mesd[‘access_token’]= $tok ;
    $mesd[‘message’]= $row->im_des ;
    $mesd[‘picture’]= ‘http://efunbox.com/’.$row->im_file;
    $mesd[‘link’]=$row->im_link ;
    $mesd[‘name’]= $row->im_alt ;

    //publish in fanpage

    try {
    $wallpostpage = $facebook->api(‘/170855269624546/feed’, ‘post’,$mesd);

    } catch (FacebookApiException $e) {
    print_r($o);
    }
    }

    this is my code
    i want to post under page title nw it posted under developer id so plz help me with rigt example

  13. Warmi January 26, 2011 at 1:30 am #

    Question for mahmud ahsan (or someone knows the answer)
    In another blog (where I can’t leave the comment) I saw you have said:
    “Facebook closed notification system for applications. So you can only send email instead of notifications.” and the question is how can I send emails to user through Graph Api, or did you refer to the old rest api?
    Thanks… !! and forget I reply in this topic :-)

    • mahmud ahsan January 26, 2011 at 12:56 pm #

      Hello Warmi, this is very simple, using extended permission you can get user’s email address. And if you use php just use mail() function to send email in that address.

  14. Warmi January 26, 2011 at 11:22 pm #

    Ah, ok, thank you… I asked you because actually I’m using the Old Rest Api method notification.sendEmail() because of the api didn’t provide us the user email address.. but now I want to migrate to graph api, so I wanted to know how to make this action possible.
    Thanks again…!

  15. n8nie January 27, 2011 at 1:19 pm #

    Hi…I’m trying to get all my tagged photos…
    I tried to use the code u provided…But I’m getting an empty array. Is there smth i missing off??

    Code:-

    try {
    $photos = $facebook->api(“/me/photos”);
    }
    catch(Exception $o) {
    print_r($o);
    }
    echo ”;
    print_r($photos);
    echo ”;

  16. Tihomir January 28, 2011 at 3:55 pm #

    Dear Mahmud,

    First of all great blog!

    I search net to found way to display fan page founded (created date) .. do you know some way?
    I can’t find any info in documentation and still haven’t ideas in dev. forum.

    Tanks and best wishes,
    Tihomir

  17. Armin Hierstetter January 30, 2011 at 7:51 pm #

    Hi Mahmud,

    this just works fine. One question regarding posting on my Fan page. When I post there using your code, it looks like that I posted it rather than my application.

    Is there a way that the post does not show me as the sender but my applcation?

    Cheers,

    Armin

  18. amelie February 20, 2011 at 3:31 am #

    Hi Mahmud,
    I am developing an iframe application and would like to get following details:
    >total application users count till now.
    >whether the application user has liked my application or not.
    Please help me with this.

  19. Abubaker March 13, 2011 at 11:41 pm #

    mahmood, once again like always great post. I would like to ask on thing that is it possible to “make a picture as your profile picture” from within our facebook application through code ? I couldn;t find such thing.. so was wondering whether is it possible to do so….Here is a detailed process that I wanted to have:
    1. User upload a picture (on my server) within my facebook application
    2. Then the user have option to make the uploaded picture as “Make Profile Picture”.

    One thing I came up with was first I will upload that uploaded photo to application album in a User’s account.. After that I don;t have a clue to do ,,,, PLease help..!

    • mahmud ahsan March 14, 2011 at 10:12 am #

      Using api you can upload pictures, but there is no way/api to make that as profile picture.

      • Abubaker March 14, 2011 at 8:49 pm #

        Thank you.. :-) This is exactly what I found on facebook developers Forum… How does iPhone do that ? it gives you an option to make an uploaded picture as your profile picture.. ? :S

  20. jack March 22, 2011 at 12:44 pm #

    hi

    how create accounts using php curl or any other solution there

  21. jack March 22, 2011 at 12:44 pm #

    how to create facebook accounts using php curl or any other solution there

  22. Prash May 13, 2011 at 6:19 pm #

    I want to know that the way to notify or call a PHP page when anyone share my link and also who share my link.

  23. Paul May 25, 2011 at 6:00 am #

    Mahmud,
    I am posting to a user’s wall, something like what you have in step 3. I am in iOS, but the basic operations are similar, just done through Facebook iOS SDK calls.

    My question is this: When I do this, the post appears on the wall, but while the link associated with the title of the post is exactly what I asked for, the link attached to the picture has the query string ?ref=nf added to the end. I gather Facebook adds this to tell somebody (?) where the link came from, and it can safely be ignored if you don’t care, except in my case the link is shortened via goo.gl, and the extra characters break the link.

    I have surveyed my own news feed and see this sometimes and not others. In my own posting, the query string does not appear to be appended if I post directly to the wall, but only when I post through my app.

    Any idea how to suppress the query string on the picture link? Is this something you see as well?

    Thanks for any help you can offer.

    • mahmud ahsan May 25, 2011 at 12:13 pm #

      Paul, I’m facing serious problem using iOS sdk and feed publish. Today I checked and found Feed publishing is not working for some of my apps and for some apps feed publish works but only publish to user’s profile wall not home feed. I used the following code for iOS. http://developers.facebook.com/docs/reference/dialogs/feed/

      • Paul May 25, 2011 at 10:10 pm #

        Mahmud,
        Thanks for your reply. I have not been having any trouble in my app with the feed itself, but the issue I am referring to actually is not iOS specific. In fact, the link that you included, namely
        http://developers.facebook.com/docs/reference/dialogs/feed/

        Shows exactly the issue I am talking about in a web based app. If you scroll to “Example” and click where it says “Click here to try the url yourself”, you’ll get a Post To Your Wall page. If you click publish and then go to your own wall, you will see that the link for the image and the link for the title are different, with the image link including the extra query string. Which is what I want to suppress. So there is something happening in the FB backend doing this that I want to suppress.

        Interestingly, before you publish, you can hover over the image and the title, and the reverse it true. The title link has the extra query string but the image link is clean. Bizarre.

        Thanks,
        Paul

      • sanjay June 25, 2011 at 1:27 pm #

        Hello mahmud,

        who i know whether user like my application or not..?

  24. sanjay June 6, 2011 at 3:25 pm #

    i tried to get facebook userdata but i got error…
    Exception Object
    (
    [message:protected] => Facebook needs the JSON PHP extension.
    [string:private] =>
    [/code] => 0
    [file:protected] => /projects/p41/www/html/interworld.co.in/RechargeNation/facebook_rd/facebook.php
    [line:protected] => 6
    [trace:private] => Array
    (
    [0] => Array
    (
    [file] => /projects/p41/www/html/interworld.co.in/RechargeNation/facebook_rd/fbmain.php
    [line] => 7
    [function] => include_once
    )
    )
    )
    i dont have install json…..
    can i use xml instead of json….plz explain the way where i can use xml …in place of json_decode…..so that i need not to install json
    plz help

  25. sanjay June 13, 2011 at 12:23 pm #

    how we know , user has been cilick like button

  26. manjesh June 15, 2011 at 11:24 pm #

    I have developed some facebook apps using php sdk. I am usng similar code as u suggested in this article.

    But when user comes to my app very first time then after getting the required permission my apps are opening out side the facebook iframe.

    can u please suggest me… why its opening outside the facebook ifreame.

    • sanjay June 16, 2011 at 3:47 pm #

      manjesh,

      This is because Facebook loses all of the authentication variables and is unable to determine that the concurrent requests belong to the same session, which results in “breaking out” of the iframe and ending up on your own server pages instead of within Facebook.

    • sanjay June 16, 2011 at 3:49 pm #

      In order to persist the session within your iframe app without breaking out to your server, you must include these parameters on each link’s query string. Here is a simple function that will produce the query string for you, so you simply need to append the result of this function to each link URL in your application:

  27. manjesh June 15, 2011 at 11:26 pm #

    <?php
    //facebook application
    //set facebook application id, secret key and api key here

    $fbconfig['appid' ] = "xxxxxxxxxxxxxxxxx";
    $fbconfig['api' ] = "xxxxxxxxxxxxxxxxxx";
    $fbconfig['secret'] = "xxxxxxxxxxxxxxxxx";

    //set application urls here
    $fbconfig['baseUrl'] = "http://www.bestblinddate.com/fbapps/lifeafter2011/&quot;;
    $fbconfig['appBaseUrl'] = "http://apps.facebook.com/life_after_year/&quot;;

    $uid = null; //facebook user id

    try{
    include_once "facebook.php";
    }
    catch(Exception $o){
    echo '';
    print_r($o);
    echo ”;
    }
    // Create our Application instance.
    $facebook = new Facebook(array(
    ‘appId’ => $fbconfig[‘appid’],
    ‘secret’ => $fbconfig[‘secret’],
    ‘cookie’ => true,
    ));

    //Facebook Authentication part
    $session = $facebook->getSession();
    $loginUrl = $facebook->getLoginUrl(
    array(
    ‘canvas’ => 1,
    ‘fbconnect’ => 0,
    ‘req_perms’ => ‘publish_stream’
    )
    );
    $fbme = null;

    if (!$session) {
    echo “top.location.href = ‘$loginUrl';”;
    exit;
    }
    else {
    try {
    $uid = $facebook->getUser();
    $fbme = $facebook->api(‘/me’);

    } catch (FacebookApiException $e) {
    echo “top.location.href = ‘$loginUrl';”;
    exit;
    }
    }

    function d($d){
    echo ”;
    print_r($d);
    echo ”;
    }
    ?>

  28. sanjay June 16, 2011 at 3:44 pm #

    Facebook Apps and iFrames are installed on servers outside of Facebook and are ‘called in & displayed’ by Facebook when the user clicks on the application or iFrame.This information is generally NOT stored on servers with SSL Certificates, ie https, rather standard http servers, and so, as it is not considered ‘secure’ Facebook will NOT display the App/iFrame through the https connection.

    Facebook User (https) Facebook (https) … OK
    Facebook User (https) Facebook (https) App/iFrame (http) … NO!

    If the App/iFrame is stored on https servers …
    Facebook User (https) Facebook (https) App/iFrame (https) … OK

    If not the only way to access the App/iFrame is to switch back to the standard http connection, ie.”untick” the https secure browsing setting.

    WebPimp.biz has implemented a SSL Certificate on its iFrame servers and modifying all links to https, this will ensure that our iFrame Tabs work with both http & https connections.

  29. sanjay June 25, 2011 at 1:26 pm #

    how i know who like my application..?

  30. rquotes July 20, 2011 at 2:04 am #

    Looking for Love Quotes to woo your soulmate? Searching for sweet love sayings to reinforce a great romance? This is the place to be – Romantic-Quotes.com is the hottest love quotes and romantic site on the net…..Enjoy…

  31. Vestal watches August 10, 2011 at 6:07 pm #

    Great share, I’m currently in process of creating something similar..

  32. Anwaltsbüro Luzern August 14, 2011 at 11:32 pm #

    This should be very helpful! Thanks.

  33. Randhu August 24, 2011 at 9:28 pm #

    Such,

    I wonder if you can show pictures of the fans of my page, I found that I can display a list of pictures of my friends, but it would be like a page (fans) can?

  34. Tom September 3, 2011 at 6:19 pm #

    Is there any way to upload photos to a fan page through Graph API ?
    I am only able to upload to profile page.

    The main idea is to to give opportunity to upload photos to fanpage and display them.
    I was able only to show the photos for the album from the fanpage.

    I will appreciate Your help

  35. canon5dreviews September 23, 2011 at 12:10 am #

    We adore taking that approach. Thx :)

  36. Tara November 3, 2011 at 3:35 am #

    Hi,

    I have reviewed the Graph API docs online and did not find any guidance on how to pass in a line break as part of the message parameter. I tried \n, /n, but none of these work. Has anyone had success with this?

    Thanks!
    Tara

  37. jigs April 3, 2012 at 1:35 pm #

    This is the best article. Thanks..

  38. jigs April 3, 2012 at 2:45 pm #

    Hi

    can we get data of
    http://developers.facebook.com/docs/reference/plugins/recommendations/

    using facebook php-sdk.?

    It is very imp for me.

    Let me know, if there is any way.

    Thanks.
    Waiting for reply…

  39. Cherise Holguin May 25, 2012 at 1:13 pm #

    composed by sbsbsb0416 Great stuff from you, my friend. Ive read your posts before and you’re just Awesome! I love what you’ve got here, love what you’re saying and the way you say it. You make it entertaining and yet you still manage to keep it smart & to the point. I cant wait to read more from you. This is really a great & very well blog!

Trackbacks/Pingbacks

  1. online play racing game - March 17, 2012

    buy xbox…

    If you do not know where you are heading, you’re never lost….