What it is
Tweepy is a Python library for accessing the Twitter API easily. It provides a convenient interface to retrieve tweets, post updates, manage followers, and interact with Twitter data programmatically.
Tweepy allows you to authenticate with Twitter, access timelines, post tweets, search for tweets, follow users, and stream live data. It supports both the REST API and the streaming API with Pythonic syntax.
Installation
pip install tweepyGetting started
The smallest useful thing you can do with it, and what each part means.
import tweepy
consumer_key = 'YOUR_CONSUMER_KEY'
consumer_secret = 'YOUR_CONSUMER_SECRET'
access_token = 'YOUR_ACCESS_TOKEN'
access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET'
auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)
print('Authentication successful')api.update_status('Hello Tweepy!')Advanced usage
Where the library earns its place over a simpler alternative.
tweets = api.user_timeline(screen_name='twitter', count=5)
for tweet in tweets:
print(tweet.text)for tweet in tweepy.Cursor(api.search_tweets, q='Python', lang='en').items(10):
print(tweet.created_at, tweet.text)class MyStream(tweepy.Stream):
def on_status(self, status):
print(status.text)
stream = MyStream(consumer_key, consumer_secret, access_token, access_token_secret)
stream.filter(track=['Python'], languages=['en'])api.create_friendship(screen_name='twitter')api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- tweepy.errors.TweepyException
- Catch general exceptions related to Twitter API requests.
- tweepy.errors.RateLimitError
- Wait until rate limits reset or use the `wait_on_rate_limit` parameter.
- tweepy.errors.Unauthorized
- Check that your API keys, access tokens, and permissions are correct.
Best practices
- Keep API keys and access tokens secure using environment variables.
- Use cursors for paginated endpoints to handle large datasets efficiently.
- Handle exceptions for rate limits and network errors gracefully.
- Use streaming API for real-time tweet collection and REST API for historical data.
- Respect Twitter’s terms of service and rate limits to avoid suspension.
Background
Why it exists, and what it was reacting to.
Tweepy was created by Joshua Roesslein in 2009 to simplify interaction with the Twitter API. It abstracts authentication, request handling, and rate limits, enabling developers to focus on building applications and collecting social media data without dealing with raw HTTP requests.
