2 Cool Things You Can Do with the Facebook Graph API

Share this article

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.

Frequently Asked Questions (FAQs) about Facebook Graph API

What is the Facebook Graph API and how does it work?

The Facebook Graph API is a tool that allows developers to read from and write data into Facebook. It presents a simple, consistent view of the Facebook social graph, uniformly representing objects in the graph (e.g., people, photos, events, and pages) and the connections between them (e.g., friend relationships, shared content, and photo tags).

How can I use the Facebook Graph API?

To use the Facebook Graph API, you need to create a Facebook App and get an access token. This token is used to make API requests on behalf of a user. The API is based on HTTP, so you can use it with any language that has an HTTP library, such as cURL.

What are the benefits of using the Facebook Graph API?

The Facebook Graph API provides developers with a powerful tool to access and manipulate a wide range of data on Facebook. It allows you to integrate your app or website with Facebook to reach its billions of users. You can read, write, and update Facebook objects through the API, making it a versatile tool for social media integration.

What are the limitations of the Facebook Graph API?

While the Facebook Graph API is a powerful tool, it does have some limitations. For instance, not all data is accessible through the API. Some user data is private and cannot be accessed without the user’s explicit permission. Additionally, the API rate limits the number of calls an app can make.

How can I handle errors in the Facebook Graph API?

The Facebook Graph API uses standard HTTP status codes to indicate success or failure of an API request. In case of an error, the API returns a JSON object with an error code and a message explaining the error. You should implement error handling in your code to deal with these situations.

Can I use the Facebook Graph API to post on a user’s behalf?

Yes, you can use the Facebook Graph API to post on a user’s behalf. However, this requires the ‘publish_actions’ permission, which must be granted by the user. Note that Facebook has strict guidelines on how this feature can be used to prevent spammy behavior.

How can I test my Facebook Graph API requests?

Facebook provides a tool called the Graph API Explorer. This tool allows you to make API requests without writing any code. You can use it to test your requests and see the responses in real-time.

How can I ensure the security of my Facebook Graph API usage?

To ensure the security of your Facebook Graph API usage, you should always use an encrypted connection (HTTPS), never include your access token in client-side code, and regularly review and update your app’s permissions.

Can I use the Facebook Graph API to access data from Facebook Pages?

Yes, you can use the Facebook Graph API to access data from Facebook Pages. This includes public posts, comments, likes, and shares. However, to access private data, you need the ‘manage_pages’ permission.

How can I paginate through results in the Facebook Graph API?

The Facebook Graph API uses cursor-based pagination to paginate through results. This means that each response includes a ‘next’ and ‘previous’ cursor that you can use to navigate through the results. You can specify the number of results per page using the ‘limit’ parameter.

Shaumik DaityariShaumik Daityari
View Author

Shaumik is a data analyst by day, and a comic book enthusiast by night (or maybe, he's Batman?) Shaumik has been writing tutorials and creating screencasts for over five years. When not working, he's busy automating mundane daily tasks through meticulously written scripts!

facebook apifacebook contestfacebook graph apifacebook mass comment
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week