Skip to content

Instantly share code, notes, and snippets.

@jkuruzovich
Forked from espeed/fbme.py
Created February 3, 2017 18:28
Show Gist options
  • Save jkuruzovich/b8485a368f80a3b88df46326cf54bbce to your computer and use it in GitHub Desktop.
Save jkuruzovich/b8485a368f80a3b88df46326cf54bbce to your computer and use it in GitHub Desktop.
Facebook Graph API Example in Python
# Facebook Graph API Example in Python
# by James Thornton, http://jamesthornton.com
# Facebook API Docs
# https://developers.facebook.com/docs/graph-api/using-graph-api#reading
# Get Your Facebook Access Token Here...
# https://developers.facebook.com/tools/explorer/145634995501895/?method=GET&path=me
# Before running this script...
# Set your Facebook Access Token as an environment variable in your terminal:
# $ export ACCESS_TOKEN={YOUR ACCESS TOKEN}
# To download this script, use the curl command...
# $ curl -O https://gist.githubusercontent.com/espeed/11114604/raw/a233d14604ea44f9d29af02cd2768b91caaad7af/fbme.py
# To run this script, use the python command to execute the script in your terminal...
# $ python fbme.py
import os
import json
import urllib
import pprint
# get Facebook access token from environment variable
ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
# build the URL for the API endpoint
host = "https://graph.facebook.com"
path = "/me"
params = urllib.urlencode({"access_token": ACCESS_TOKEN})
url = "{host}{path}?{params}".format(host=host, path=path, params=params)
# open the URL and read the response
resp = urllib.urlopen(url).read()
# convert the returned JSON string to a Python datatype
me = json.loads(resp)
# display the result
pprint.pprint(me)
@WJTey
Copy link

WJTey commented Jul 20, 2017

Hi,the access_token here need user access token or app access token? Need to replace the actual token at
26 ACCESS_TOKEN = os.environ['ACCESS_TOKEN']
OR
31 params = urllib.urlencode({"access_token": ACCESS_TOKEN})

I get key error msg when run the cells.

@warisali2
Copy link

@WJTey You need to set Access Token as environment variable before running the script or you can just put it in your code at line 26
ACCESS_TOKEN = {Your Access Token Here}
Type of access token depends upon the type type of request you are making. For example, if want to request something on the behalf of the user, you need to use user access token.

@alfredrumss
Copy link

@warisali2 how to make a request to the access_token api ? I want to generate it because the same one expires if generate it on the https://developers.facebook.com/

@Gwairia
Copy link

Gwairia commented Jan 5, 2019

this error message appear:
urllib.error.HTTPError: HTTP Error 400: Bad Request

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