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?
8 Answers
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.
-
2The official one! You can get it from GitHub: github.com/facebook/python-sdk I updated the answer to include the link. Mar 28, 2012 at 19:11
-
2
-
6By this exampe, it loks lik this SDK was pretty much useless as well - I suggest using the "requests" Python library for the http comunication instead: pypi.python.org/pypi/requests– jsbuenoMar 3, 2013 at 23:27
-
-
This doesn't work anymore anyway, as the response given now is a JSON document, not a query string.– Martijn Pieters ♦Jun 21, 2018 at 11:45
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']
-
-
2As of writing, this endpoint returns JSON, so change
result = file.text.split("=")[1]
toresult = file.json()['access_token']
Oct 25, 2017 at 8:38 -
1
-
This isn't true - it gets a full access token, the same as with the official facebook-sdk (see answer below). Why it is shorter than the access token you get through the web fb-dev page: These are long-lived access tokens, the ones you get through the web are short-live tokens only valid for a few hours (these appear to be longer). So the answer from Waqas is probably the best because it doesn't require you to install the facebook-sdk just for getting the token.– AlexOct 29, 2019 at 4:38
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)
-
Hey, is it safe to store app_secret in code like that? Facebook documentation explicitly states " Again, for security, app access token should never be hard-coded into client-side code, doing so would give everyone who loaded your webpage or decompiled your app full access to your app secret, and therefore the ability to modify your app." Oct 23, 2015 at 20:45
-
1No you shouldn't include the app secret in client side code. But the question here implies interactive/server usage, not client-side code.– s29Nov 4, 2015 at 6:08
-
This answer is the best answer, but could be dramatically improved by giving actual working code. In particular, point to the 'installation' docs for the facebook SDK, and then show how to
import facebook
, construct a client object, and then callget_app_access_token
on that object. Aug 2, 2018 at 15:05
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
-
Thank you so much for giving us a link to how to set up an application! Jul 10, 2018 at 16:51
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
-
@daaku So in order to regenerate an expired access token for a user I need to redirect their web browser to Facebook (I'm guessing so Facebook can read it's own cookies to identify the user)?– NeilFeb 6, 2012 at 10:36
-
Deprecated, I guess they don't want to allow automated tools. As someone who needs to develop them this move to oauth-only by the leading websites is disturbing... Mar 19, 2012 at 1:42
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:
- 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).
- 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
- 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.
- follow the redirects until it sends you back to your site, and get the "code" parameter out of that URL
- 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!
-
wow, that in theory sounds very nice, have you done something like that in python?– Alg_DJan 19, 2017 at 23:25
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
).
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/
-
Thanks, I saw that, but I'm looking for a stand alone script. This is part of a Django app or something is it not?– justinhjJun 18, 2010 at 23:36
-
-