I’ve got a python flask app whose job is to work with the Twitter V2.0 API. I got to using the Tweepy API in my app because I was having difficulty cold coding the 3 legged auth flow. Anyway, since I got that working, I’m now running into difficulties executing some basic queries, like get_me() and get_user()
This is my code:
client = tweepy.Client(
consumer_key=private.API_KEY,
consumer_secret=private.API_KEY_SECRET,
access_token=access_token,
access_token_secret=access_token_secret)
user = client.get_me(expansions='author_id', user_fields=['username','created_at','location'])
print(user)
return('success')
And this is invariably the error:
tweepy.errors.BadRequest: 400 Bad Request
The expansions
query parameter value [author_id] is not one of [pinned_tweet_id]
Per the Twitter docs for this endpoint, this should certainly work…I fail to understand why I the ‘pinned_tweet_id’ expansion is the particular issue.
I’m left wondering if I’m missing something basic here or if Tweepy is just a POS and I should considering rolling my own queries like I originally intended.
2
Answers
The solution is to drop the 'expansions' kwag and leave 'user_fields' as is. I was further confused by the fact that printing the returned user object does not show the requested user_fields as part of the data attribute. You have to explicitly access them through the data attribute, as below.
Tweet Author ID
You may have read the Twitter Docs incorrectly as the expansions parameter value has only
pinned_tweet_id
, and the tweet fields parameter has theauthor_id
value you’re looking for. Here is a screenshot for better clarification:The code would look like:
User ID
If you’re looking for the user id then try omitting tweet_fields and add
id
in theuser_fields
also shown in the Twitter Docs.The code would look like:
You can obtain the user id with
user.data.id
.