Blog

How to retrieve Facebook extra info from Django

VM Vera Mazhuga Vera Mazhuga

Vera Mazhuga

Software Developer
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 settings.py file:

SOCIAL_AUTH_FACEBOOK_SCOPE = [
    'email',
    'user_friends',
    'friends_location',
]


So when a user will try to log in to our website using his Facebook account,
he
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
token
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="https://graph.facebook.com/{0}/'">https://graph.facebook.com/{0}/'</a> \
          u'friends?fields=id,name,location,picture' \
          u'&access;_token={1}'.format(
              social_user.uid,
              social_user.extra_data['access_token'],
          )
    request = urllib2.Request(url)


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

{
   "data":[
      {
         "id":"uid",
         "name":"John Doe",
         "location":{
            "id":"id",
            "name":"Bogotá, Colombia"
         },
         "picture":{
            "data":{
               "url":"avatar url",
               "is_silhouette":false
            }
         }
      }
   ]
}

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

Written by Vera Mazhuga

VM Vera Mazhuga Vera Mazhuga

Vera specializes in writing and maintaining code for various applications. Her focus on problem-solving and efficient programming ensures reliable and effective software solutions.

Scale your company with the same people

Practical ideas to do more and get back your time every week

We respect your inbox. Privacy policy

Wait. There's more:

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

1 min read.

Build to
Inspire