Skip to content

Instantly share code, notes, and snippets.

@atinsood
Last active December 17, 2015 12:29
Show Gist options
  • Save atinsood/5609989 to your computer and use it in GitHub Desktop.
Save atinsood/5609989 to your computer and use it in GitHub Desktop.
Basic lookup using facebook graph api without using the auth token.
import requests
import pprint
import facebook
import json
FB_APP_CLIENT_ID = ''
FB_APP_CLIENT_SECRET = ''
FB_MY_USER_ID = ''
def writeTokenToFile(token):
with open('tokenFile', 'w') as tokenFile:
tokenFile.write(token)
def readTokenFromFile():
with open('tokenFile', 'r') as tokenFile:
token = tokenFile.read()
return token
def getAccessToken():
fbUrl = 'https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=' \
+ FB_APP_CLIENT_ID + '&client_secret=' + FB_APP_CLIENT_SECRET
r = requests.get(fbUrl)
access_token = r.text.split('=')[1]
return access_token
def getInfoAboutMe(token):
r = requests.get('https://graph.facebook.com/' + FB_MY_USER_ID, params={'access_token': token})
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(r.json())
def getInfoAboutFriends(token):
friendsUrl = "?fields=id,name,friends.fields(last_name,first_name,gender)"
r = requests.get('https://graph.facebook.com/' + FB_MY_USER_ID + friendsUrl, params={'access_token': token})
data = r.json()
friends = data['friends']
count = len(friends['data'])
#pp = pprint.PrettyPrinter(indent=4)
#pp.pprint(r.json())
print(count)
def tryOpenGraph(token):
graph = facebook.GraphAPI(token)
profile = graph.get_object(FB_MY_USER_ID)
friends = graph.get_connections(FB_MY_USER_ID, "friends",
fields="last_name,first_name,gender")
print(json.dumps(profile, indent=4, separators=(',', ': ')))
print(json.dumps(friends, indent=4, separators=(',', ': ')))
def readConfigFile():
import ConfigParser
config = ConfigParser.SafeConfigParser()
config.read('details.txt')
global FB_APP_CLIENT_ID, FB_APP_CLIENT_SECRET, FB_MY_USER_ID
FB_APP_CLIENT_ID = config.get('Credentials', 'FB_APP_CLIENT_ID')
FB_APP_CLIENT_SECRET = config.get('Credentials', 'FB_APP_CLIENT_SECRET')
FB_MY_USER_ID = config.get('Credentials', 'FB_MY_USER_ID')
if __name__ == '__main__':
readConfigFile()
token = readTokenFromFile()
print('found token to be {0}'.format(token))
if token is None or len(token.strip()) == 0:
print('Getting a new token')
token = getAccessToken()
writeTokenToFile(token)
#getInfoAboutMe(token)
#getInfoAboutFriends(token)
tryOpenGraph(token)
@atinsood
Copy link
Author

Updated the gist to use the python facebook SDK https://github.com/pythonforfacebook/facebook-sdk/

Note that how we are referring to ourself using the FB_ID vs me.

@atinsood
Copy link
Author

Added code to read the app id, app secret and user id from a config file. The format of the file can be

[Credentials]
FB_APP_CLIENT_ID :
FB_APP_CLIENT_SECRET :
FB_MY_USER_ID :

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment