I’m trying to retrieve some sample recent tweets from X using Python’s Tweepy package. I am authenticating my API call with API Key, API Key Secret, Access Token, and Access Token Secret generated from a developer project within my own X account.
import tweepy
client = tweepy.Client(
consumer_key=consumer_key,
consumer_secret=consumer_secret,
access_token=access_token,
access_token_secret=access_token_secret
)
query = <query-string>
client.search_recent_tweets(query=query)
But I keep getting Unauthorized: 401 Unauthorized
error.
I tried app-only authentication using my X Bearer Token but got the same error.
client = tweepy.Client(bearer_token=os.environ.get('BEARER_TOKEN'))
Note that this issue is occurring with Twitter API v2 which has replaced v1.1. This question has been asked before within the last year or so: here and here but there are no answers on either thread.
In case you do not have a resolution for the 401 error, suggestions for alternative Python packages for retrieving tweets from X are also welcome.