Language: Python
Web
The Facebook SDK for Python was developed to make it easier for Python developers to integrate Facebook services into their applications. It abstracts HTTP requests to the Graph API and handles authentication, permissions, and API responses in a Pythonic way, enabling social media integrations, analytics, and automation tasks.
The Facebook SDK for Python is a library that allows developers to interact with the Facebook Graph API. It provides tools for posting content, retrieving user data, managing pages, and working with Facebook Ads programmatically.
pip install facebook-sdkconda install -c conda-forge facebook-sdkThe SDK allows you to authenticate with Facebook, send requests to the Graph API, post to pages or timelines, read user or page data, and handle responses. It supports OAuth 2.0 authentication and can be used for apps, bots, or analytics.
import facebook
access_token = 'YOUR_ACCESS_TOKEN'
graph = facebook.GraphAPI(access_token=access_token, version='3.1')Creates a GraphAPI client instance using your access token to authenticate requests.
profile = graph.get_object('me')
print(profile)Retrieves the authenticated user's profile information from Facebook.
graph.put_object(parent_object='me', connection_name='feed', message='Hello Facebook!')Posts a simple status message to the authenticated user's timeline.
graph.put_photo(image=open('photo.jpg', 'rb'), message='Check out this photo!')Uploads an image to the authenticated user's timeline with a caption.
page_feed = graph.get_connections('your_page_id', 'feed')
for post in page_feed['data']:
print(post['message'])Retrieves posts from a Facebook page's feed and prints their messages.
feed = graph.get_connections('me', 'feed')
while True:
for post in feed['data']:
print(post['message'])
if 'next' in feed.get('paging', {}):
feed = requests.get(feed['paging']['next']).json()
else:
breakIterates through paginated results to process all items in a feed.
graph.delete_object('post_id')Deletes a specific post by its ID.
import hmac, hashlib
app_secret = 'YOUR_APP_SECRET'
appsecret_proof = hmac.new(app_secret.encode('utf-8'), access_token.encode('utf-8'), hashlib.sha256).hexdigest()
graph.get_object('me', appsecret_proof=appsecret_proof)Adds an extra layer of security when making API calls by using appsecret_proof.
Use long-lived access tokens for server-side applications.
Handle API rate limits gracefully and implement retries.
Use proper permissions scopes to access the data needed.
Keep your app secret and access tokens secure using environment variables.
Validate all responses and handle exceptions to prevent runtime errors.