Tweepy API: unable to get queries to return user_fields

Question:

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.

Asked By: userBrett97

||

Answers:

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 the author_id value you’re looking for. Here is a screenshot for better clarification:

Twitter Docs

The code would look like:

    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(tweet_fields=['author_id'], user_fields=[
                     'username', 'created_at', 'location'])
    print(user)
    return('success')

User ID

If you’re looking for the user id then try omitting tweet_fields and add id in the user_fields also shown in the Twitter Docs.
Twitter Docs 2

The code would look like:

    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(user_fields=['id', 'username', 'created_at', 'location'])
    print(user)
    return('success')

You can obtain the user id with user.data.id.

Answered By: bytro

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.

code

result

Answered By: userBrett97
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.