2 Cool Things You Can Do with the Facebook Graph API

By Shaumik Daityari
We teamed up with SiteGround
To bring you the latest from the web and tried-and-true hosting, recommended for designers and developers. SitePoint Readers Get Up To 65% OFF Now

In December 2011, Facebook officially deprecated its REST API and launched the Graph API for public use. Since then, all new features have been added to the Graph API and Facebook has enabled users to perform loads of new things, some of which we will discuss today. In this post, we will be making a lot of requests to the Graph API, receiving JSON responses, and thereby manipulating them to get our desired results.

The Access Token

Most requests to the Graph API need an access token as a parameter. An access token is unique to the combination of a logged in user or page and the Facebook App that makes the request.

A token is associated with a Facebook app to handle the permissions that the user has granted to the app. This defines the resources that are accessible through the access token. Thus, a token provides temporary and secure access to Facebook. You can get an access token from the Graph Explorer. A token may or may not have an exipry time depending on whether they are short-term or long-term tokens. After the expiry of a short-term token, you need to re-authenticate the user and get a new token.

Contests Through Facebook Pages

In recent times, small and up-and-coming organizations have used Facebook pages effectively to promote their content. Yet, getting ‘likes’ and thus, increasing your reach, is a slow and steady process. Many turn to Facebook ads for this purpose. Many others, though, take a cheaper alternative — by organizing contests through their page.

The usual contest involves posting a photo or a paragraph on the page about an experience. The contest is judged on the basis of the number of ‘likes’ on the post or the photo. There’s also an extra condition for participating in the contest. For a ‘like’ to be valid, the user needs to like the page too. Facebook doesn’t have any built-in feature that tells you how many likes are common to your post and page. That makes judging the contests difficult.

Non-programmers would feel that the only way to judge the contest is by cross checking the number of likes manually. Fortunately, the Graph API helps us perform this action without much hassle.

Although I am going to perform the action through Python, the process remains the same for other languages. The important part is the target URLs that we send the requests to and the data we get from the received JSON.

A conceptually easy way to do this would be to get the list of likes on a post and the list of likes on a page and then compare them. However, there is no functionality in Facebook that gets the list of likes on a page as of now. We will use the reverse process to check whether each like on a post likes the page as well.

The following call checks whether a user likes a page or not. The detailed documentation is available here.

GET /{user-id}/likes/{page-id}

If the user likes the page, the JSON response contains data about the page, but if the user doesn’t like the page, an empty data is received. We use the following function to determine if a user likes a page or not.

def user_likes_page(user_id, page_id):
        Returns whether a user likes a page
    url = 'https://graph.facebook.com/%d/likes/%d/' % (user_id, page_id)
    parameters = {'access_token': TOKEN}
    r = requests.get(url, params = parameters)
    result = json.loads(r.text)
    if result['data']:
        return True
        return False

The next step is to get the list of likes for a particular post and find out whether the users likes the page too. The following call gives us the list of likes for a post, provided we have proper access.

GET /{post-id}/likes/

Combining the two ideas, we make the following function to check how many likes in a post are common to the page too.

def get_common_likes(post_id, page_id):
        Returns the number of likes common to a post and the page
    count_likes = 0
    url = 'https://graph.facebook.com/%d/likes/' % post_id
    parameters = {'access_token': TOKEN}
    r = requests.get(url, params = parameters)
    result = json.loads(r.text)
    for like in result['data']:
        if user_likes_page(int(like['id']), page_id):
            count_likes += 1
            print 1
    return count_likes

Mass Responding to Posts on Your Timeline

On your birthday, I am sure you get hundreds (if not thousands) of posts. Replying to each of them is tedious! Many people put up a status thanking everyone for their wishes, while others prefer to thank each one personally. Let us see how we can choose the personal option and do it in a short amount of time.

The call to get the feed for users or pages is as follows.

GET /{user-id}/feed

In case you want to get the posts on your timeline, you can replace {user-id} with ‘me’, which makes the process look easier. To manipulate hundreds and thousands of posts, you would not be able to get them in a single page. You would need to go a step ahead and check the next url in the JSON response.

The function that gets all the posts on your timeline is as follows.

def get_posts():
        Returns the list of posts on my timeline

    parameters = {'access_token': TOKEN}
    r = requests.get('https://graph.facebook.com/me/feed', params=parameters)
    result = json.loads(r.text)
    return result['data']

The next step is to publish comments on your timeline. The call that is used to perform this action is as follows.

POST /{object-id}/comments

The comment should be sent as a message in the POST request above. So, the function that we use to comment on posts is as follows.

def comment_on_posts(posts):
    """Comments on all posts"""
    for post in posts:
        url = 'https://graph.facebook.com/%s/comments' % post['post_id']
        message = 'Commenting through the Graph API'
        parameters = {'access_token': TOKEN, 'message': message}
        s = requests.post(url, data = parameters)

The scripts that I have used for both of these can be found on GitHub. In addition, you can take it one step further by making multiple API requests at the same time.

An Alternative Approach

Akshit Khurana, on Quora, discusses another approach to this through the use of Facebook Query Language (FQL). FQL is an SQL-like language that lets you query the data that you receive through the Graph API. There is a list of tables, each with its own list of columns that can be queried, thus helping you filter your data.


Facebook has been working hard since the launch of the Graph API and new features are being added to it frequently. If you plan to work on mobile or web applications that are linked to Facebook, the use of the Graph API is a must. Facebook also maintains extensive documentation, which explains in detail the features and variety of uses of the Graph API.

We teamed up with SiteGround
To bring you the latest from the web and tried-and-true hosting, recommended for designers and developers. SitePoint Readers Get Up To 65% OFF Now
  • SRD75

    You have a spelling mistake: “recevived”

    • OphelieLechat

      Fixed, thanks for letting us know!

  • lfx

    Nice article with 2 useful topics! Thank you :)

  • Hello,
    I have two questions if you have a minute.

    I have problems to understand how I create a Access Token with long time . I create a app but I dont know what is the platform that I must to select if I will work with a script in python. Also I create the acces token here https://developers.facebook.com/tools/explorer/ but only one hour and all the times I must to create one.
    I not find nothing in internet more to resolve this. This is the only solution of this.

    The second question is send my attach to a page not my personal page

    attach = {
    “name”: ‘Hello’,
    “link”: ‘http://www.link.com’,
    “caption”: ‘test’,
    “description”: ‘some test’,
    “picture” : ‘http://www.eltiempo24h.eu/images/logo.jpg’,

    Thank you
    Sorry my bad english.

  • walid

    Its possible to get total likes/comments in one single request using graph API 2 istead of using counter by iterating object in get_common_likes(post_id, page_id)


    Here is link to Graph API v2.0 doc about this topic : https://developers.facebook.com/docs/graph-api/reference/v2.0/object/comments

    • imraj


  • Astrount

    Very nice and thank you :) I have a question, when I fetch posts from my wall and I try to open one of them via Facebook Android application I fail, as the returned posts IDs are not the same posts IDs you get when you hover over the post time (via PC browser). How to solve this when I use this technique [ return new Intent(Intent.ACTION_VIEW, Uri.parse(“fb://post/” + aUserID + “_” + postId)); ]

  • prem

    Nice. can you tell how to get total checkin count. As we can get likes count using page_fan (lifetime)

  • Andrew Von Pelt III

    Is it possible to get pages that a page likes? i.e. publicly I can see that a page likes 3 other pages and i’d like to get that data back in an api…

  • Raesh Sharma

    Can i get friend list and friend of friends list using any of facebook APIs for android??

  • aroraprateek202112

    Is it possible to get the user phone number from Graph Api.

    • If the user has shared it with you, it is.

      • aroraprateek202112

        Can you guide me, how to enable the sharing of phone number on Facebook, so graph Api can access it.

        • I don’t think it would be accessible unless the user explicitly shares it.

  • Monali Nimje

    Is it possible, Can we get user’s data that which user has like our post ? Is facebook provide any api for this? please suggest me any suggestion

  • Тарас Поліщук

    How to get all my comments written ever for any posts (not mine) in facebook?