11

How can I retrieve Facebook friend's information using Python-Social-auth and Django? I already retrieve a profile information and authenticate the user, but I want to get more information about their friends and invite them to my app. Thanks!

Bruno Paulino
  • 5,611
  • 1
  • 41
  • 40
  • 1
    Check http://stackoverflow.com/a/20998857/385822, that answer talks about user likes, but the same can be applied to friends once you find the Facebook API that returns the needed data. – omab Mar 21 '14 at 15:56

2 Answers2

13

You can do it using Facebook API. Firstly, you need obtain the token of your Facebook application (FACEBOOK_APP_ACCESS_TOKEN) https://developers.facebook.com/tools/accesstoken/ or from social_user.extra_data['access_token']

Then with this token you can send the requests you need, for example, this code gets all the friends of the authenticated user with their id, name, location, picture:

social_user = request.user.social_auth.filter(
    provider='facebook',
).first()
if social_user:
    url = u'https://graph.facebook.com/{0}/' \
          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)
    friends = json.loads(urllib2.urlopen(request).read()).get('data')
    for friend in friends:
        # do something

Depending on what fields you want to get you can set the permissions here: https://developers.facebook.com/apps/ -> Your App -> App Details -> App Centre Permissions

or set your permissions in settings.py:

SOCIAL_AUTH_FACEBOOK_SCOPE = [
    'email',
    'user_friends',
    'friends_location',
]
cansadadeserfeliz
  • 3,033
  • 5
  • 34
  • 50
  • I I have to get Email and access_token for Gmail User will the social_user = request.user.social_auth.filter( provider='google-oauth2', ) work out? – arshpreet Jul 28 '15 at 11:35
  • You are not using the app_secretproof like you would if you are calling from a secure server (client in Oauth2 terminology) – spencer.pinegar May 06 '20 at 17:09
1

Just some extra for the reply above. To get the token from extra_data you need to import the model with that data (took me a while to find this): from social.apps.django_app.default.models import UserSocialAuth

Michael
  • 40
  • 4