Understanding Facebook Graph API and implementing in Python, Django

(Comments)

The Graph API is the primary way to get data out of, and put data into, Facebook's platform. It's a low-level HTTP-based API that you can use to programmatically query data, post new stories, manage ads, upload photos, and perform a variety of other tasks that an app might implement.

To be able to get data from facebook or modify data on facebook, you need to register as developer on facebook and have an access token.

Let's see how can we register for a developer account for facebook.

1) Go to link developers.facebook.com, create an account there.

2) Go to link developers.facebook.com/tools/explorer.

3) Go to “My apps” drop down in the top right corner and select “add a new app”. Choose a display name and a category and then “Create App ID”.

alt text

4) Once again go to explorer developers.facebook.com/tools/explorer. You will see “Graph API Explorer” below “My Apps” in the top right corner. From “Graph API Explorer” drop down, select your app.

5) Then, select “Get Token”. From this drop down, select “Get User Access Token”. Select permissions from the menu that appears and then select “Get Access Token.”

6) Go to link developers.facebook.com/tools/accesstoken. Select “Debug” corresponding to “User Token”. Go to “Extend Token Access”. This will ensure that your token does not expire every two hours.

The Graph API

The Graph API has multiple versions available, the latest version at the time of writing this article is 2.9. You can learn more about the versions changelog here.

Go to https://developers.facebook.com/docs/graph-api/reference/v2.9. This documentation provides reference to various fields from which you want to extract data. Some of the mostly used fields are "Event", "Group", "Post" etc., from which you can extract data. Check out the below screenshot for reference.

alt text

In this article, we will see how can we get the data from a Facebook Group.

alt text

First of all create a variable called "USER_ACCESS_TOKEN" and set its value to what you got above as “User Access Token” and "GROUP_ID" for the group you want to fetch data from. see example code snippet below. This is a sample token and group_id, replace it with your access token and group_id.

#facebook user access token

USER_ACCESS_TOKEN = 'abcdefghijklmnopqrstuvwxyzABCDEfghijklmnopqrstuvwxyz'

#facebook group ID

GROUP_ID = '935150123456789'

Also make sure that you have python 'requests' and 'urllib3' installed. If not follow the below instructions and install.

$ pip install requests

$ pip install urllib3

Now let's fetch the group name, privacy and other details using the python requests.

First create a variable called parameters and run the following commands.

parameters = {'access_token': USER_ACCESS_TOKEN}

group_url = 'https://graph.facebook.com/%d/' % GROUP_ID

r = requests.get(group_url, params=parameters)

To see the response run r.json(). The sample output is as shown below.

{
  "name": "Test",
  "privacy": "OPEN",
  "id": "935150123456789"
}

If there is an error, one of the reason might be that the access token is expired. In that case 'r.json()["error"]["code"]' will give you a error code '190'. In that case we need to refresh the access token. And to refresh the access token we need the 'App ID' and 'App Secret' of your facebook app.

Let's see how can we get those data.

Go to the link https://developers.facebook.com/apps. You will see all your apps listed. Select the app for which you want to get the 'App ID' and 'App Secret'. Refer the below screenshot.

alt text

To see the App Secret, click on show button. Once you got the 'App ID' and 'App Secret', follow the code snippet below to refresh the 'user access token'.

app_id = 'your app id'
app_secret = 'your app secret'
url = "https://graph.facebook.com/oauth/access_token?grant_type=" \
    "client_credentials&client_id=%s&client_secret=%s" % \
    (client_id, client_secret)
r = requests.get(url)

access_token = r.text.split('=')[1]

Let's go through the code. First we created two variables 'app_id' and 'app_secret'. Replace 'your app id' and 'your app secret' with the details we got from here https://developers.facebook.com/apps. Refer above screenshot.

Once again we used python requests to get the new token. You can now use this 'user access token' to make requests to Graph API.

To make this process simple you can follow one of the following steps.

1) Store the 'App ID' and 'App Secret' in your Django project settings.py file.

2) Other way is to use django-allauth and add your facebook app to your project.

First one is straight forward and don't need any installation as such. The second needs to install django-allauth app to your project. The easy way to install it is using the pip.

pip install django-allauth

Add the following lines to your settings.py file.

# Specify the context processors as follows:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # Already defined Django-related contexts here

                # `allauth` needs this from django
                'django.template.context_processors.request',
            ],
        },
    },
]

AUTHENTICATION_BACKENDS = (
    ...
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
    ...
)

INSTALLED_APPS = (
    ...
    # The following apps are required:
    'django.contrib.auth',
    'django.contrib.sites',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',

For more detailed information about 'django-allauth' go to this page http://django-allauth.readthedocs.io/en/latest/index.html

Getting Feed from the Facebook Group

alt text

We can get the feed from the facebook group using the python requests as shown below.

feed_url = 'https://graph.facebook.com/%s/feed/' \
        '?since=%s&fields=attachments,likes,comments.limit(3)' \
        '{comments.limit(3),message,id,created_time,from},message,' \
        'from,updated_time,parent_id' % \
        (group_id, timestamp)

The 'timestamp' is datetime from which you want get the feed to the latest available.

This way you can use the Facebook API to get the group feed. Like wise there are many things you can do like posting, reading number of likes, etcc., For more Details about using different fields go through the reference docs here https://developers.facebook.com/docs/graph-api/reference/v2.9/.

Comments

Recent Posts

Archive

2021
2020
2019
2018
2017
2016
2015
2014

Tags

Authors

Feeds

RSS / Atom