Tweepy - Python client for X API
Tweepy is a popular, easy-to-use Python library for accessing the X API (formerly Twitter API). It provides a Pythonic way to interact with both v1.1 and v2 of the API, handling authentication, requests, and response parsing. The current version is 4.16.0, and it generally releases new versions frequently, often tied to changes or additions in the X API.
Warnings
- breaking Tweepy v4.15.0 and newer dropped support for Python 3.7 and 3.8. Users on these older Python versions must upgrade to Python 3.9 or newer to use the latest Tweepy versions.
- breaking Twitter API v1.1 streaming methods (e.g., `Stream.sample`, `AsyncStream.sample`) were removed in Tweepy v4.13.0 due to Twitter API retirement of these features.
- gotcha A crucial distinction exists between `tweepy.API` (for Twitter API v1.1) and `tweepy.Client` (for Twitter API v2). They use different authentication schemes (OAuth 1.0a vs. Bearer Token/OAuth 2.0 PKCE) and target different API versions. Using the wrong client for an endpoint will result in errors.
- gotcha Twitter API v2 authentication via `tweepy.Client` primarily uses Bearer Tokens for public data access. For user-specific actions (e.g., posting tweets, sending DMs, liking), OAuth 2.0 with PKCE or OAuth 1.0a User Context is required, which is more complex to set up and manage.
- gotcha The Twitter API has strict rate limits. Exceeding these limits will result in `tweepy.TweepyException` (specifically a 429 HTTP error for 'Too Many Requests'). Continuously hitting rate limits can lead to temporary blocks.
Install
-
pip install tweepy
Imports
- Client
from tweepy import Client
- API
from tweepy import API
- StreamingClient
from tweepy import StreamingClient
- OAuth1UserHandler
from tweepy import OAuth1UserHandler
- TweepyException
from tweepy import TweepyException
Quickstart
import os
import tweepy
# For Twitter API v2, using a Bearer Token (read-only for public data)
bearer_token = os.environ.get("TWITTER_BEARER_TOKEN", "YOUR_BEARER_TOKEN")
if not bearer_token or bearer_token == "YOUR_BEARER_TOKEN":
print("Warning: TWITTER_BEARER_TOKEN environment variable not set or is default. Quickstart may fail.")
print("To run this example, set TWITTER_BEARER_TOKEN or replace 'YOUR_BEARER_TOKEN' with an actual key.")
try:
client = tweepy.Client(bearer_token)
# Example: Get recent tweets by a user
username = "tweepy"
response = client.get_user(username=username)
user_data = response.data
if user_data:
user_id = user_data.id
print(f"User ID for @{username}: {user_id}")
response = client.get_users_tweets(user_id, tweet_fields=["created_at", "author_id"], max_results=5)
if response.data:
print(f"Latest tweets from @{username}:")
for tweet in response.data:
print(f"- [{tweet.created_at.strftime('%Y-%m-%d %H:%M')}] {tweet.text}")
else:
print(f"No tweets found for @{username}.")
else:
print(f"User @{username} not found or error occurred.")
except tweepy.TweepyException as e:
print(f"An error occurred with Tweepy: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")