Open Facebook API¶
Open Facebook allows you to use Facebook’s open graph API with simple python code
Features
- Supported and maintained
- Tested so people can contribute
- Facebook exceptions are mapped
- Logging
Basic examples:
facebook = OpenFacebook(access_token)
# Getting info about me
facebook.get('me')
# Learning some more about fashiolista
facebook.get('fashiolista')
# Writing your first comment
facebook.set('fashiolista/comments', message='I love Fashiolista!')
# Posting to a users wall
facebook.set('me/feed', message='check out fashiolista',
url='http://www.fashiolista.com')
# Liking a page
facebook.set('fashiolista/likes')
# Getting who likes cocacola
facebook.set('cocacola/likes')
# Use fql to retrieve your name
facebook.fql('SELECT name FROM user WHERE uid = me()')
# Executing fql in batch
facebook.batch_fql([
'SELECT uid, name, pic_square FROM user WHERE uid = me()',
'SELECT uid, rsvp_status FROM event_member WHERE eid=12345678',
])
# Uploading pictures
photo_urls = [
'http://e.fashiocdn.com/images/entities/0/7/B/I/9/0.365x365.jpg',
'http://e.fashiocdn.com/images/entities/0/5/e/e/r/0.365x365.jpg',
]
for photo in photo_urls:
print facebook.set('me/feed', message='Check out Fashiolista',
picture=photo, url='http://www.fashiolista.com')
Getting an access token
Once you get your access token, Open Facebook gives you access to the Facebook API There are 3 ways of getting a facebook access_token and these are currently implemented by Django Facebook.
- code is passed as request parameter and traded for an
- access_token using the api
- code is passed through a signed cookie and traded for an access_token
- access_token is passed directly (retrieved through javascript, which
- would be bad security, or through one of the mobile flows.)
If you are looking to develop your own flow for a different framework have a look at Facebook’s documentation: http://developers.facebook.com/docs/authentication/
Also have a look at the FacebookRequired
decorator and get_persistent_graph()
function to
understand the required functionality
Api docs:
-
class
open_facebook.api.
OpenFacebook
(access_token=None, prefetched_data=None, expires=None, current_user_id=None, version=None)[source]¶ The main api class, initialize using
Example:
graph = OpenFacebook(access_token) print(graph.get('me'))
-
batch_fql
(queries_dict)[source]¶ queries_dict a dict with the required queries returns the query results in:
Example:
response = facebook.batch_fql({ name: 'SELECT uid, name, pic_square FROM user WHERE uid = me()', rsvp: 'SELECT uid, rsvp_status FROM event_member WHERE eid=12345678', }) # accessing the results response['fql_results']['name'] response['fql_results']['rsvp']
Parameters: queries_dict – A dictiontary of queries to execute Returns: dict
-
delete
(path, *args, **kwargs)[source]¶ Delete the given bit of data
Example:
graph.delete(12345)
Parameters: path – the id of the element to remove
-
fql
(query, **kwargs)[source]¶ Runs the specified query against the Facebook FQL API.
Example:
open_facebook.fql('SELECT name FROM user WHERE uid = me()')
Parameters: - query – The query to execute
- kwargs – Extra options to send to facebook
Returns: dict
-
get
(path, version=None, **kwargs)[source]¶ Make a Facebook API call
Example:
open_facebook.get('me') open_facebook.get('me', fields='id,name')
Parameters: path – The path to use for making the API call Returns: dict
-
get_many
(*ids, **kwargs)[source]¶ Make a batched Facebook API call For multiple ids
Example:
open_facebook.get_many('me', 'starbucks') open_facebook.get_many('me', 'starbucks', fields='id,name')
Parameters: path – The path to use for making the API call Returns: dict
-
get_request_url
(path='', old_api=False, version=None, **params)[source]¶ Gets the url for the request.
-
has_permissions
(required_permissions)[source]¶ Validate if all the required_permissions are currently given by the user
Example:
open_facebook.has_permissions(['publish_actions','read_stream'])
Parameters: required_permissions – A list of required permissions Returns: bool
-
my_image_url
(size='large')[source]¶ Returns the image url from your profile Shortcut for me/picture
Parameters: size – the type of the image to request, see facebook for available formats Returns: string
-
permissions
()[source]¶ Shortcut for self.get(‘me/permissions’) with some extra parsing to turn it into a dictionary of booleans
Returns: dict
-
set
(path, params=None, version=None, **post_data)[source]¶ Write data to facebook
Example:
open_facebook.set('me/feed', message='testing open facebook')
Parameters: - path – The path to use for making the API call
- params – A dictionary of get params
- post_data – The kwargs for posting to facebook
Returns: dict
-
-
class
open_facebook.api.
FacebookAuthorization
[source]¶ Methods for getting us an access token
There are several flows we must support * js authentication flow (signed cookie) * facebook app authentication flow (signed cookie) * facebook oauth redirect (code param in url) These 3 options need to be converted to an access token
Also handles several testing scenarios * get app access token * create test user * get_or_create_test_user
-
classmethod
convert_code
(code, redirect_uri='http://local.mellowmorning.com:8000/facebook/connect/')[source]¶ Turns a code into an access token
Example:
FacebookAuthorization.convert_code(code)
Parameters: - code – The code to convert
- redirect_uri – The redirect uri with which the code was requested
Returns: dict
-
classmethod
create_test_user
(app_access_token, permissions=None, name=None)[source]¶ Creates a test user with the given permissions and name
Parameters: - app_access_token – The application’s access token
- permissions – The list of permissions to request for the test user
- name – Optionally specify the name
-
classmethod
extend_access_token
(access_token)[source]¶ https://developers.facebook.com/roadmap/offline-access-removal/ We can extend the token only once per day Normal short lived tokens last 1-2 hours Long lived tokens (given by extending) last 60 days
Example:
FacebookAuthorization.extend_access_token(access_token)
Parameters: access_token – The access_token to extend Returns: dict
-
classmethod
get_app_access_token
()[source]¶ Get the access_token for the app that can be used for insights and creating test users application_id = retrieved from the developer page application_secret = retrieved from the developer page returns the application access_token
-
classmethod
get_or_create_test_user
(app_access_token, name=None, permissions=None, force_create=False)[source]¶ There is no supported way of get or creating a test user However - creating a test user takes around 5s - you an only create 500 test users So this slows your testing flow quite a bit.
This method checks your test users Queries their names (stores the permissions in the name)
-
classmethod
parse_signed_data
(signed_request, secret='0aceba27823a9dfefa955f76949fa4b4')[source]¶ Thanks to http://stackoverflow.com/questions/3302946/how-to-base64-url-decode-in-python and http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas
-
classmethod
-
class
open_facebook.api.
FacebookConnection
[source]¶ Shared utility class implementing the parsing of Facebook API responses
-
classmethod
is_server_error
(e, response)[source]¶ Checks an HTTPError to see if Facebook is down or we are using the API in the wrong way Facebook doesn’t clearly distinquish between the two, so this is a bit of a hack
-
classmethod
match_error_code
(error_code)[source]¶ Return the right exception class for the error code
-
classmethod
raise_error
(error_type, message, error_code=None)[source]¶ Lookup the best error class for the error and raise it
Example:
FacebookConnection.raise_error(10, 'OAuthException')
Parameters: - error_type – the error type from the facebook api call
- message – the error message from the facebook api call
- error_code – optionally the error code which facebook send
-
classmethod
request
(path='', post_data=None, old_api=False, **params)[source]¶ Main function for sending the request to facebook
- Example::
- FacebookConnection.request(‘me’)
Parameters: - path – The path to request, examples: /me/friends/, /me/likes/
- post_data – A dictionary of data to post
- parms – The get params to include
-
classmethod