To enable users to create and publish content on Threads via your app, you must implement an OAuth flow using ThreadsGraphAPI.
- Initialize
ThreadsGraphAPI: Provide your app_id, app_secret, set oauth_flow=True, define your redirect_uri, and specify the required scope (e.g., threads_basic, threads_content_publish). - Get Authorization URL: Call
api.get_authorization_url() to generate the URL where the user must authorize your app. - Exchange Code for Token: After the user authorizes, they will be redirected to your
redirect_uri with a code parameter in the URL. Pass this full redirected URL to api.exchange_user_access_token(response="...") to retrieve the access_token and user_id.
from pyfacebook import ThreadsGraphAPI
api = ThreadsGraphAPI(
app_id="Your app id",
app_secret="Your app secret",
oauth_flow=True,
redirect_uri="Your callback domain",
scope=[
"threads_basic",
"threads_content_publish",
"threads_read_replies",
"threads_manage_replies",
"threads_manage_insights"
]
)
# 1. Get the URL for the user to visit
auth_url = api.get_authorization_url()
print(f"Authorize here: {auth_url}")
# 2. After redirection, exchange the response URL for a token
# Example response URL: https://example.com/callback?code=AQBZzYhLZB&state=PyFacebook#_
token_data = api.exchange_user_access_token(response="Your response url")
print(token_data)
# Output: {'access_token': 'access_token', 'user_id': 12342412}