Skip to content

Instantly share code, notes, and snippets.

@sparack
Created April 14, 2022 00:31
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save sparack/e8021298115f4a1289a637e25f284daf to your computer and use it in GitHub Desktop.
Save sparack/e8021298115f4a1289a637e25f284daf to your computer and use it in GitHub Desktop.
A guide to migrating your code in Python that uses Tweepy from the Twitter API v1.1 to the Twitter API v2

Guide to migrating your code from Twitter API v1.1 to v2 with Tweepy in Python

Tweepy is a popular library that allows developers to interact with the Twitter API in Python. Since the launch of the new Twitter API v2, Tweepy has been updated to support the new API. Many students and developers continue to use the old Twitter API v1.1 in Tweepy, because they are unware of the new API v2 or because they do not know how to migrate their code to use v2.

In this guide, I will show you how you can migrate your Tweepy code in Python that uses the old Twitter API v1.1 to use the new Twitter API v2.

In order to use the Twitter API, you first need to sign up for access. Once you have access, you need to get your keys and tokens from the developer portal to connect to the Twitter API. To learn how to get your keys and tokens based on your access levels, check out the How to get your API Keys and tokens section in this guide.

Initializing your Tweepy client and authentication

Twitter API v1.1 Twitter API v2
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
auth.set_access_token('ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET')
client = tweepy.API(auth)
import tweepy

client = tweepy.Client("BEARER_TOKEN")

Searching Tweets from the last 7 days

Twitter API v1.1 Twitter API v2
Endpoint: search/tweets Endpoint: recent search
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
client = tweepy.API(auth)

tweets = client.search_tweets(q='covid', count=100)

for tweet in tweets:
    print(tweet.id_str)
import tweepy

client = tweepy.Client('BEARER_TOKEN')

tweets = client.search_recent_tweets(query='covid', max_results=100)

for tweet in tweets.data:
    print(tweet.id)

Learn more about writing search queries here

Getting more than 100 Tweets from the last 7 days

Twitter API v1.1 Twitter API v2
Endpoint: search/tweets Endpoint: recent search
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
client = tweepy.API(auth)

for tweet in tweepy.Cursor(client.search_tweets, q='covid',
                           count=100).items(250):
    print(tweet.id_str)
import tweepy

client = tweepy.Client(bearer_token='REPLACE_ME')

for tweet in tweepy.Paginator(client.search_recent_tweets, query='covid', 
                              max_results=100).flatten(limit=250):
    print(tweet.id)

Searching Tweets from the entire archive of public Tweets

Twitter API v1.1 Twitter API v2
Endpoint: premium search Endpoint: full-archive search
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
client = tweepy.API(auth)

tweets = client.search_full_archive(query='covid', 
                                    label='dev', maxResults=100)

for tweet in tweets:
    print(tweet.id_str)
import tweepy

client = tweepy.Client('BEARER_TOKEN')

tweets = client.search_all_tweets(query='covid', max_results=100)

for tweet in tweets.data:
    print(tweet.id)

Looking up Tweets using Tweet IDs

Twitter API v1.1 Twitter API v2
Endpoint: statuses/lookup Endpoint: Tweets lookup
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
client = tweepy.API(auth)
  
id = [20, 1503863303709286407, 1460323737035677698]

tweets = client.lookup_statuses(id=id)

for tweet in tweets:
    print(tweet.text)
import tweepy

client = tweepy.Client('BEARER_TOKEN')

ids = [20, 1503863303709286407, 1460323737035677698]

tweets = client.get_tweets(ids=ids)

for tweet in tweets.data:
    print(tweet.text)

Looking up users using user IDs

Twitter API v1.1 Twitter API v2
Endpoint: users/lookup Endpoint: Users lookup
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
client = tweepy.API(auth)
  
user_id = [857699969263964161, 2244994945]

users = client.lookup_users(user_id=user_id)

for user in users:
    print(user.screen_name)
import tweepy

client = tweepy.Client('BEARER_TOKEN')

ids = [857699969263964161, 2244994945]
  
users = client.get_users(ids=ids)

for user in users.data:
    print(user.username)

Getting a user's timeline

Twitter API v1.1 Twitter API v2
Endpoint: statuses/user_timeline Endpoint: User Timeline
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
client = tweepy.API(auth)

tweets = client.user_timeline(user_id=2244994945)

for tweet in tweets:
    print(tweet.id_str)
import tweepy

client = tweepy.Client('BEARER_TOKEN')

tweets = client.get_users_tweets(id=2244994945)

for tweet in tweets.data:
    print(tweet.id)

Getting a user's mentions

Twitter API v1.1 Twitter API v2
Endpoint: statuses/mentions_timeline Endpoint: User mentions
import tweepy
import config

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
auth.set_access_token('ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET')
client = tweepy.API(auth)

tweets = client.mentions_timeline()

for tweet in tweets:
    print(tweet.id_str)
import tweepy

client = tweepy.Client('BEARER_TOKEN')

tweets = client.get_users_mentions(id=2244994945)

for tweet in tweets.data:
    print(tweet.id)

Getting a user's followers

Twitter API v1.1 Twitter API v2
Endpoint: followers/list Endpoint: followers
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
client = tweepy.API(auth)

users = client.get_followers(user_id=2244994945)

for user in users:
    print(user.screen_name)
import tweepy

client = tweepy.Client('BEARER_TOKEN')

users = client.get_users_followers(id=2244994945)

for user in users.data:
    print(user.username)

Getting users that a user is following

Twitter API v1.1 Twitter API v2
Endpoint: get-friends-list Endpoint: following
import tweepy

auth = tweepy.OAuthHandler('API_KEY', 'API_SECRET')
client = tweepy.API(auth)

users = client.get_friends(user_id=2244994945)

for user in users:
    print(user.screen_name)
import tweepy

client = tweepy.Client('BEARER_TOKEN')

users = client.get_users_following(id=2244994945)

for user in users.data:
    print(user.username)

Streaming Tweets in real-time using the 1% sampled stream

Twitter API v1.1 Twitter API v2
Endpoint: statuses/sample Endpoint: sampled stream
import tweepy


class IDPrinter(tweepy.Stream):

    def on_status(self, status):
        print(status.id_str)


printer = IDPrinter(
  'API_KEY', 'API_SECRET',
  'ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET'
)

printer.sample()
import tweepy


class IDPrinter(tweepy.StreamingClient):

    def on_tweet(self, tweet):
        print(tweet.id)


printer = IDPrinter('BEARER_TOKEN')
printer.sample()

Filtering Tweets in real-time using the filtered stream

Twitter API v1.1 Twitter API v2
Endpoint: statuses/filter Endpoint: filtered stream
import tweepy


class IDPrinter(tweepy.Stream):

    def on_status(self, status):
        print(status.id_str)


printer = IDPrinter(
  'API_KEY', 'API_SECRET',
  'ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET'
)

printer.filter(track=["covid"])
import tweepy


class IDPrinter(tweepy.StreamingClient):

    def on_tweet(self, tweet):
        print(tweet.id)


printer = IDPrinter('BEARER_TOKEN')
printer.add_rules(tweepy.StreamRule("covid"))
printer.filter()

Additional resources

I hope this helps you in your journey of moving your Tweepy code from using the Twitter API v1.1 to using the Twitter API v2. If you have any questions, please reach out to me @suhemparack

@ar852
Copy link

ar852 commented Jan 19, 2023

Thanks! This was very helpful

@intoroddex
Copy link

intoroddex commented Apr 4, 2023

Thanks for this guide

And the stream with ids ?
how would it be in V2?
twitter_stream.filter(follow=[ids])

@ahmedmunzir
Copy link

How would we post tweets using this new API?

@MarijaErason
Copy link

Great job! One question, I have an issue finding the country (not only location) and language field of the Twitter user when getting profile/user_followers/user_followings. Has anyone stumbled on this yet? :D

@anilupss
Copy link

anilupss commented Aug 13, 2023

Hello:
I'm trying to migrate my projects to Twitter API v2, but none examples work for me. I have a free development account.
It still continues to show the same error:

tweepy.errors.Forbidden: 403 Forbidden
When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.

I need a guide to verify what it is the possible mistake.

@Fronstryns
Copy link

I'm in the same boat. Let's hope they fix/change whatever is broken with v2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment