Library for accessing the X API (Twitter)
The API class provides complete access to Twitter API v1.1 endpoints for backward compatibility and access to v1.1-specific functionality not yet available in v2. This interface is considered legacy but remains important for certain features.
Create an API instance with authentication and configuration options.
class API:
def __init__(self, auth=None, *, cache=None, host='api.twitter.com',
parser=None, proxy=None, retry_count=0, retry_delay=0,
retry_errors=None, timeout=60, upload_host='upload.twitter.com',
user_agent=None, wait_on_rate_limit=False):
"""
Initialize Twitter API v1.1 interface.
Parameters:
- auth (AuthHandler): Authentication handler object
- cache (Cache, optional): Cache implementation
- host (str): API host (default: 'api.twitter.com')
- parser (Parser, optional): Response parser
- proxy (str, optional): Proxy server URL
- retry_count (int): Number of retries on failure
- retry_delay (int): Delay between retries in seconds
- retry_errors (list, optional): HTTP status codes to retry
- timeout (int): Request timeout in seconds
- upload_host (str): Media upload host
- user_agent (str, optional): Custom user agent string
- wait_on_rate_limit (bool): Wait when rate limited
"""Access various Twitter timelines and user tweet collections.
def home_timeline(self, *, count=20, since_id=None, max_id=None, trim_user=False,
exclude_replies=False, include_entities=True):
"""
Get the authenticated user's home timeline.
Parameters:
- count (int): Number of tweets to retrieve (max 200)
- since_id (int, optional): Return results after this tweet ID
- max_id (int, optional): Return results before this tweet ID
- trim_user (bool): Trim user objects to just ID
- exclude_replies (bool): Exclude reply tweets
- include_entities (bool): Include tweet entities
Returns:
List of Status objects (tweets)
"""
def user_timeline(self, *, user_id=None, screen_name=None, count=20,
since_id=None, max_id=None, trim_user=False,
exclude_replies=False, include_rts=True):
"""
Get tweets from a specific user's timeline.
Parameters:
- user_id (int, optional): User ID
- screen_name (str, optional): Username
- count (int): Number of tweets to retrieve (max 200)
- since_id (int, optional): Return results after this tweet ID
- max_id (int, optional): Return results before this tweet ID
- trim_user (bool): Trim user objects to just ID
- exclude_replies (bool): Exclude reply tweets
- include_rts (bool): Include retweets
Returns:
List of Status objects (tweets)
"""
def mentions_timeline(self, *, count=20, since_id=None, max_id=None,
trim_user=False, include_entities=True):
"""
Get tweets mentioning the authenticated user.
Returns:
List of Status objects (mention tweets)
"""Create, retrieve, and manage tweets using v1.1 endpoints.
def update_status(self, status, *, in_reply_to_status_id=None,
auto_populate_reply_metadata=False, exclude_reply_user_ids=None,
attachment_url=None, media_ids=None, possibly_sensitive=False,
lat=None, long=None, place_id=None, display_coordinates=False,
trim_user=False, enable_dmcommands=False, fail_dmcommands=False,
card_uri=None):
"""
Post a new tweet.
Parameters:
- status (str): Tweet text content
- in_reply_to_status_id (int, optional): Tweet ID to reply to
- media_ids (list, optional): List of media IDs to attach
- possibly_sensitive (bool): Mark as potentially sensitive
- lat (float, optional): Latitude for geo location
- long (float, optional): Longitude for geo location
- place_id (str, optional): Place ID for location
Returns:
Status object (created tweet)
"""
def get_status(self, id, *, trim_user=False, include_my_retweet=True,
include_entities=True, include_ext_alt_text=True,
include_card_uri=False):
"""
Get a specific tweet by ID.
Parameters:
- id (int): Tweet ID
- trim_user (bool): Trim user objects to just ID
- include_my_retweet (bool): Include authenticated user's retweet
- include_entities (bool): Include tweet entities
Returns:
Status object (tweet)
"""
def destroy_status(self, id, *, trim_user=False):
"""
Delete a tweet.
Parameters:
- id (int): Tweet ID to delete
Returns:
Status object (deleted tweet)
"""
def retweet(self, id, *, trim_user=False):
"""
Retweet a tweet.
Returns:
Status object (retweet)
"""
def unretweet(self, id, *, trim_user=False):
"""
Remove a retweet.
Returns:
Status object (original tweet)
"""Retrieve and manage user information and relationships.
def get_user(self, *, user_id=None, screen_name=None, include_entities=True):
"""
Get user information by ID or screen name.
Parameters:
- user_id (int, optional): User ID
- screen_name (str, optional): Username
- include_entities (bool): Include user entities
Returns:
User object
"""
def lookup_users(self, *, user_ids=None, screen_names=None, include_entities=True,
tweet_mode="compat"):
"""
Get multiple users by IDs or screen names.
Parameters:
- user_ids (list, optional): List of user IDs (up to 100)
- screen_names (list, optional): List of usernames (up to 100)
Returns:
List of User objects
"""
def search_users(self, q, *, count=20, page=1, include_entities=True):
"""
Search for users.
Parameters:
- q (str): Search query
- count (int): Number of results per page (max 20)
- page (int): Page number
Returns:
List of User objects
"""
def create_friendship(self, *, user_id=None, screen_name=None, follow=True):
"""
Follow a user.
Parameters:
- user_id (int, optional): User ID to follow
- screen_name (str, optional): Username to follow
- follow (bool): Enable notifications
Returns:
User object (followed user)
"""
def destroy_friendship(self, *, user_id=None, screen_name=None):
"""
Unfollow a user.
Returns:
User object (unfollowed user)
"""Search for tweets and users using v1.1 search endpoints.
def search_tweets(self, q, *, geocode=None, lang=None, locale=None,
result_type="mixed", count=15, until=None, since_id=None,
max_id=None, include_entities=True):
"""
Search for tweets.
Parameters:
- q (str): Search query
- geocode (str, optional): Geographic search ("lat,long,radius")
- lang (str, optional): Language code
- result_type (str): "mixed", "recent", or "popular"
- count (int): Number of results (max 100)
- until (str, optional): Search until date (YYYY-MM-DD)
- since_id (int, optional): Return results after this tweet ID
- max_id (int, optional): Return results before this tweet ID
Returns:
SearchResults object with tweets and metadata
"""Manage Twitter lists using v1.1 list endpoints.
def create_list(self, name, *, mode="public", description=None):
"""
Create a new list.
Parameters:
- name (str): List name
- mode (str): "public" or "private"
- description (str, optional): List description
Returns:
List object
"""
def get_list(self, *, list_id=None, slug=None, owner_screen_name=None,
owner_id=None):
"""
Get list information.
Returns:
List object
"""
def get_lists(self, *, user_id=None, screen_name=None, reverse=False):
"""
Get lists owned by a user.
Returns:
List of List objects
"""
def list_timeline(self, *, list_id=None, slug=None, owner_screen_name=None,
owner_id=None, count=20, since_id=None, max_id=None,
include_entities=True, include_rts=True):
"""
Get tweets from a list.
Returns:
List of Status objects
"""Upload media files for use in tweets.
def media_upload(self, filename, *, file=None, chunked=False,
media_category=None, additional_owners=None):
"""
Upload media file.
Parameters:
- filename (str): Path to media file
- file (file-like, optional): File object
- chunked (bool): Use chunked upload for large files
- media_category (str, optional): Media category
- additional_owners (list, optional): Additional owner user IDs
Returns:
Media object with media_id
"""
def chunked_upload(self, filename, *, file=None, file_type=None,
media_category=None, additional_owners=None):
"""
Upload large media file in chunks.
Returns:
Media object with media_id
"""import tweepy
# Initialize with authentication
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, wait_on_rate_limit=True)
# Post a tweet
tweet = api.update_status("Hello from Tweepy v1.1 API!")
print(f"Posted tweet: {tweet.id}")
# Get home timeline
timeline = api.home_timeline(count=10)
for tweet in timeline:
print(f"@{tweet.user.screen_name}: {tweet.text}")# Search for tweets
results = api.search_tweets(q="python programming", count=20, result_type="recent")
for tweet in results:
print(f"@{tweet.user.screen_name}: {tweet.text}")
# Get user information
user = api.get_user(screen_name="twitter")
print(f"User: {user.name} (@{user.screen_name})")
print(f"Followers: {user.followers_count:,}")
# Follow a user
api.create_friendship(screen_name="python")
print("Now following @python")Note: The API class contains hundreds of methods covering all Twitter API v1.1 endpoints. This documentation covers the most commonly used methods. Refer to the full Tweepy documentation for complete v1.1 API coverage.
Install with Tessl CLI
npx tessl i tessl/pypi-tweepy