Programmatically getting an access token for using the Facebook Graph API

Question:

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?

Asked By: justinhj

||

Answers:

Here is the Python Code. Try running some of these examples on command line, they work fine for me. See also — http://www.pythonforfacebook.com/

Answered By: gsharma

You first need to set up an application. The following will then spit out an access token given your application ID and secret:

> curl -F type=client_cred -F client_id=[...] -F client_secret=[...] https://graph.facebook.com/oauth/access_token
Answered By: Ian Stevens

Since a web browser needs to be involved for the actual authorization, there is no such thing as a “standalone script” that does it all. If you’re just playing with the API, or are writing a script to automate something yourself, and want a access_token for yourself that does not expire, you can grab one here: http://fbrell.com/auth/offline-access-token

Answered By: daaku

There IS a way to do it, I’ve found it, but it’s a lot of work and will require you to spoof a browser 100% (and you’ll likely be breaking their terms of service)

Sorry I can’t provide all the details, but the gist of it:

  1. assuming you have a username/password for a facebook account, go curl for the oauth/authenticate… page. Extract any cookies returned in the “Set-Cookie” header and then follow any “Location” headers (compiling cookies along the way).
  2. scrape the login form, preserving all fields, and submit it (setting the referer and content-type headers, and inserting your email/pass) same cookie collection from (1) required
  3. same as (2) but now you’re going to need to POST the approval form acquired after (2) was submitted, set the Referer header with thr URL where the form was acquired.
  4. follow the redirects until it sends you back to your site, and get the “code” parameter out of that URL
  5. Exchange the code for an access_token at the oauth endpoint

The main gotchas are cookie management and redirects. Basically, you MUST mimic a browser 100%. I think it’s hackery but there is a way, it’s just really hard!

Answered By: Hidden

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: https://github.com/mobolic/facebook-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: https://github.com/pythonforfacebook/facebook-sdk,
  • 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 https://developers.facebook.com/docs/authentication/ for details.

This blog post might also help with this: http://blog.theunical.com/facebook-integration/5-steps-to-publish-on-a-facebook-wall-using-php/

Here goes:

#!/usr/bin/python
# 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.
FACEBOOK_APP_ID     = 'XXXXXXXXXXXXXXX'
FACEBOOK_APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
FACEBOOK_PROFILE_ID = 'XXXXXX'


# 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',
                  'https://graph.facebook.com/oauth/access_token?' + urllib.urlencode(oauth_args)]
oauth_response = subprocess.Popen(oauth_curl_cmd,
                                  stdout = subprocess.PIPE,
                                  stderr = subprocess.PIPE).communicate()[0]

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

facebook_graph = facebook.GraphAPI(oauth_access_token)


# Try to post something on the wall.
try:
    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.

Answered By: maryisdead

Easy! Just use facebook-sdk.

import facebook

app_id = 'YOUR_APP_ID'
app_secret = 'YOUR_APP_SECRET'

graph = facebook.GraphAPI()

# exactly what you're after ;-)
access_token = graph.get_app_access_token(app_id, app_secret) 
Answered By: s29

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 = 'https://graph.facebook.com/oauth/access_token'       
    payload = {
        'grant_type': 'client_credentials',
        'client_id': app_id,
        'client_secret': app_secret
    }
    response = requests.post(url, params=payload)
    return response.json()['access_token']
Answered By: Waqas

s29 has the correct answer but leaves some steps to solve. The following script demonstrates a working script for acquiring an access token using the Facebook SDK:

__requires__ = ['facebook-sdk']

import os

import facebook


def get_app_access_token():
    client = facebook.GraphAPI()
    return client.get_app_access_token(
        os.environ['FACEBOOK_APP_ID'],
        os.environ['FACEBOOK_APP_SECRET'],
    )


__name__ == '__main__' and print(get_app_access_token())

This script expects the FACEBOOK_APP_ID and FACEBOOK_APP_SECRET environment variables are set to the values for your app. Feel free to adapt that technique to load those values from a different source.

You must first install the Facebook SDK (pip install facebook-sdk; python get-token.py) or use another tool like rwt to invoke the script (rwt -- get-token.py).

Answered By: Jason R. Coombs
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.