2 Cool Things You Can Do with the Facebook Graph API

Shaumik Daityari

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
    else:
        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.

Conclusion

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.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • SRD75

    You have a spelling mistake: “recevived”

    • OphelieLechat

      Fixed, thanks for letting us know!

  • lfx

    Nice article with 2 useful topics! Thank you :)