Programmatically getting an access token for using the Facebook Graph API


I am trying to put together a bash or python script to play with the facebook graph API. Using the API looks simple, but I'm having trouble setting up curl in my bash script to call authorize and access_token. Does anyone have a working example?

6/17/2010 3:41:24 AM

Accepted Answer

Update 2018-08-23

Since this still gets some views and upvotes I just want to mention that by now there seems to exist a maintained 3rd party SDK:

Better late than never, maybe others searching for that will find it. I got it working with Python 2.6 on a MacBook.

This requires you to have

  • the Python facebook module installed:,
  • an actual Facebook app set up
  • and the profile you want to post to must have granted proper permissions to allow all the different stuff like reading and writing.

You can read about the authentication stuff in the Facebook developer documentation. See for details.

This blog post might also help with this:

Here goes:

# coding: utf-8

import facebook
import urllib
import urlparse
import subprocess
import warnings

# Hide deprecation warnings. The facebook module isn't that up-to-date (facebook.GraphAPIError).
warnings.filterwarnings('ignore', category=DeprecationWarning)

# Parameters of your app and the id of the profile you want to mess with.

# Trying to get an access token. Very awkward.
oauth_args = dict(client_id     = FACEBOOK_APP_ID,
                  client_secret = FACEBOOK_APP_SECRET,
                  grant_type    = 'client_credentials')
oauth_curl_cmd = ['curl',
                  '' + urllib.urlencode(oauth_args)]
oauth_response = subprocess.Popen(oauth_curl_cmd,
                                  stdout = subprocess.PIPE,
                                  stderr = subprocess.PIPE).communicate()[0]

    oauth_access_token = urlparse.parse_qs(str(oauth_response))['access_token'][0]
except KeyError:
    print('Unable to grab an access token!')

facebook_graph = facebook.GraphAPI(oauth_access_token)

# Try to post something on the wall.
    fb_response = facebook_graph.put_wall_post('Hello from Python', \
                                               profile_id = FACEBOOK_PROFILE_ID)
    print fb_response
except facebook.GraphAPIError as e:
    print 'Something went wrong:', e.type, e.message

Error checking on getting the token might be better but you get the idea of what to do.

8/23/2018 9:36:50 AM

Here you go, as simple as it can get. Doesn’t require any 3rd-party SDK etc.

Make sure Python 'requests' module is installed

import requests

def get_fb_token(app_id, app_secret):
    url = ''       
    payload = {
        'grant_type': 'client_credentials',
        'client_id': app_id,
        'client_secret': app_secret
    response =, params=payload)
    return response.json()['access_token']

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow