Library for accessing the X API (Twitter)
Tweepy provides comprehensive authentication support for different Twitter API access patterns through multiple OAuth handlers. Each handler supports different application types and use cases, from simple app-only access to full user authorization flows.
OAuth 1.0a User Context authentication enables applications to act on behalf of a specific Twitter user, providing access to user-specific endpoints and data.
class OAuth1UserHandler:
def __init__(self, consumer_key, consumer_secret, access_token=None,
access_token_secret=None, callback=None):
"""
Initialize OAuth 1.0a User Context authentication handler.
Parameters:
- consumer_key (str): Consumer key from Twitter app dashboard
- consumer_secret (str): Consumer secret from Twitter app dashboard
- access_token (str, optional): User's access token
- access_token_secret (str, optional): User's access token secret
- callback (str, optional): Callback URL for authorization flow
"""
def get_authorization_url(self, signin_with_twitter=False, access_type=None):
"""
Get authorization URL for user to grant access to the application.
Parameters:
- signin_with_twitter (bool): Use Sign in with Twitter flow (default: False)
- access_type (str, optional): "read" or "write" access level
Returns:
tuple: (authorization_url, request_token_secret)
"""
def get_access_token(self, verifier=None):
"""
Exchange authorization verifier for access token.
Parameters:
- verifier (str, optional): OAuth verifier from callback or PIN
Returns:
tuple: (access_token, access_token_secret)
"""
def set_access_token(self, key, secret):
"""
Set access token and secret (deprecated - use constructor parameters).
Parameters:
- key (str): Access token
- secret (str): Access token secret
"""
def apply_auth(self):
"""
Apply authentication to HTTP requests.
Returns:
OAuth1 authentication object for requests
"""import tweepy
# Initialize handler with app credentials
auth = tweepy.OAuth1UserHandler(
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret",
callback="http://localhost:3000/callback"
)
# Get authorization URL
auth_url, request_token_secret = auth.get_authorization_url()
print(f"Please authorize: {auth_url}")
# After user authorizes, get verifier and exchange for access token
verifier = input("Enter verifier: ")
access_token, access_token_secret = auth.get_access_token(verifier)
# Create client with user authentication
client = tweepy.Client(
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret",
access_token=access_token,
access_token_secret=access_token_secret
)
# Now you can make user-authenticated requests
user = client.get_me()
print(f"Authenticated as: {user.data.username}")OAuth 2.0 Bearer Token authentication provides app-only access for applications that don't need to act on behalf of specific users.
class OAuth2BearerHandler:
def __init__(self, bearer_token):
"""
Initialize OAuth 2.0 Bearer Token authentication handler.
Parameters:
- bearer_token (str): Bearer token from Twitter app dashboard
"""
def apply_auth(self):
"""
Apply authentication to HTTP requests.
Returns:
HTTPBearerAuth authentication object for requests
"""import tweepy
# Simple bearer token authentication
client = tweepy.Client(bearer_token="your_bearer_token")
# Make app-only requests
tweets = client.search_recent_tweets(query="python programming", max_results=10)
for tweet in tweets.data:
print(tweet.text)OAuth 2.0 App-Only authentication uses consumer credentials to obtain a bearer token programmatically.
class OAuth2AppHandler:
def __init__(self, consumer_key, consumer_secret):
"""
Initialize OAuth 2.0 App-Only authentication handler.
Parameters:
- consumer_key (str): Consumer key from Twitter app dashboard
- consumer_secret (str): Consumer secret from Twitter app dashboard
"""
def apply_auth(self):
"""
Apply authentication to HTTP requests.
Returns:
HTTPBasicAuth authentication object for requests
"""import tweepy
# OAuth 2.0 App-Only authentication
auth = tweepy.OAuth2AppHandler(
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret"
)
# Use with legacy API
api = tweepy.API(auth)
tweets = api.search_tweets(q="python programming", count=10)OAuth 2.0 Authorization Code Flow with PKCE enables user authentication for modern applications with enhanced security.
class OAuth2UserHandler:
def __init__(self, *, client_id, redirect_uri, scope, client_secret=None):
"""
Initialize OAuth 2.0 Authorization Code Flow with PKCE.
Parameters:
- client_id (str): OAuth 2.0 client ID from Twitter app dashboard
- redirect_uri (str): Registered redirect URI
- scope (list): List of requested scopes
- client_secret (str, optional): Client secret (for confidential clients)
"""
def get_authorization_url(self):
"""
Get authorization URL for user to grant access.
Returns:
tuple: (authorization_url, state, code_verifier)
"""
def fetch_token(self, authorization_response):
"""
Exchange authorization code for access token.
Parameters:
- authorization_response (str): Full authorization response URL
Returns:
dict: Token response with access_token, refresh_token, etc.
"""import tweepy
# OAuth 2.0 Authorization Code Flow with PKCE
oauth2_handler = tweepy.OAuth2UserHandler(
client_id="your_client_id",
redirect_uri="http://localhost:3000/callback",
scope=["tweet.read", "tweet.write", "users.read", "offline.access"]
)
# Get authorization URL
auth_url, state, code_verifier = oauth2_handler.get_authorization_url()
print(f"Please authorize: {auth_url}")
# After user authorizes and returns to callback
authorization_response = input("Enter full callback URL: ")
token = oauth2_handler.fetch_token(authorization_response)
# Create client with OAuth 2.0 user token
client = tweepy.Client(bearer_token=token["access_token"])
# Make user-authenticated requests
user = client.get_me()
print(f"Authenticated as: {user.data.username}")Tweepy provides backward compatibility aliases for older authentication class names.
class OAuthHandler(OAuth1UserHandler):
"""Deprecated alias for OAuth1UserHandler (use OAuth1UserHandler instead)"""
class AppAuthHandler(OAuth2AppHandler):
"""Deprecated alias for OAuth2AppHandler (use OAuth2AppHandler instead)"""The Client class accepts authentication credentials directly in its constructor:
# Method 1: Direct credential parameters
client = tweepy.Client(
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret",
access_token="your_access_token",
access_token_secret="your_access_token_secret"
)
# Method 2: Bearer token only
client = tweepy.Client(bearer_token="your_bearer_token")
# Method 3: Mixed authentication (bearer token + user credentials)
client = tweepy.Client(
bearer_token="your_bearer_token",
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret",
access_token="your_access_token",
access_token_secret="your_access_token_secret"
)The legacy API class uses authentication handler objects:
# OAuth 1.0a User Context
auth = tweepy.OAuth1UserHandler(
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret",
access_token="your_access_token",
access_token_secret="your_access_token_secret"
)
api = tweepy.API(auth)
# OAuth 2.0 Bearer Token
auth = tweepy.OAuth2BearerHandler(bearer_token="your_bearer_token")
api = tweepy.API(auth)
# OAuth 2.0 App-Only
auth = tweepy.OAuth2AppHandler(
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret"
)
api = tweepy.API(auth)StreamingClient requires a bearer token for authentication:
# Streaming authentication (bearer token required)
stream = tweepy.StreamingClient(bearer_token="your_bearer_token")Different API endpoints require different authentication contexts:
These operations require user authentication (user_auth=True):
These operations work with app-only authentication:
Authentication errors are represented by specific exception types:
class Unauthorized(HTTPException):
"""401 Unauthorized - Invalid or missing authentication credentials"""
class Forbidden(HTTPException):
"""403 Forbidden - Valid credentials but insufficient permissions"""Different authentication contexts have different rate limits:
Configure rate limit handling in the client:
# Wait when rate limit is exceeded
client = tweepy.Client(
bearer_token="your_bearer_token",
wait_on_rate_limit=True
)Install with Tessl CLI
npx tessl i tessl/pypi-tweepy