How to retrieve Facebook extra info from Django

Photo of the author: Vera Mazhuga

Vera Mazhuga


1 min read.

When we use python-social-auth sometimes there is a need to obtain
some extra information from the Facebook about a registered user. Let's look at
how to retrieve a list of friends and their location.

To specify to which fields we need to have access, we need to add them to SOCIAL_AUTH_FACEBOOK_SCOPE list in file:


So when a user will try to log in to our website using his Facebook account,
will be asked
if our application can access his personal data:

In our case the app will ask him for his email, list of his friends and their location.

If the user agrees,
python-social-auth will create an instance of SocialUser clas with the following attributes:

As we can see, accessing
extra_data JSON, we can get a Facebook
will allow us to get the extra information we need via Facebook API.
Firstly, we get an
SocialUser object:

<pre lang="python">social_user = request.user.social_auth.filter(<br/> provider='facebook',<br/>).first()<br/></pre>

Since we got it, we can sent a GET request to Facebook API, passing
the user's
uid, access token and a list of fields we want to obtain:

if social_user:
    url = u'<a href="{0}/'">{0}/'</a> \
          u'friends?fields=id,name,location,picture' \
    request = urllib2.Request(url)

The API returns us a JSON with the data we requested:

         "name":"John Doe",
            "name":"Bogotá, Colombia"
               "url":"avatar url",

So now we can load it co a Python dictionary:

    friends = json.loads(urllib2.urlopen(request).read()).get('data')
    for friend in friends:
        location = friend.get('location')
        # do something

Get a monthly update from our CEO.

Learn about how we think.

Imagen vs. Diseño digital

Durante muchos años, se ha venido hablando sobre que la buena imagen de una página web, trae consigo más clientes y una mayor...

Author Roberto Aguirre Roberto Aguirre

Own your tech to own your destiny