Search code examples
twittertwitterapi-python

Twitter API 2.0 - Unable to fetch user.fields


I am using API version 2.0 and unable to fetch the user.fields results. All other parameters seem to be returning results correctly. I'm following this documentation.

url = "https://api.twitter.com/2/tweets/search/all"

query_params = {
    "query": "APPL",
    "max_results": "10",
    "tweet.fields": "created_at,lang,text,author_id",
    "user.fields": "name,username,created_at,location",
    "expansions": "referenced_tweets.id.author_id",
}

response = requests.request("GET", url, headers=headers, params=query_params).json()

Sample result:

{
  'author_id': '1251347502013521925',
  'text': 'All conspiracy. But watch for bad news on Apple.  Such a vulnerable stocktechnically for the biggest market cap @ $2.1T ( Thanks Jay). This is the glue for the bulls. But, they stopped innovating when Steve died, built a fancy office and split the stock. $appl',
  'lang': 'en',
  'created_at': '2021-06-05T02:33:48.000Z',
  'id': '1401004298738311168',
  'referenced_tweets': [{
    'type': 'retweeted',
    'id': '1401004298738311168'
  }]
}

As you can see, the following information is not returned: name, username, and location.

Any idea how to retrieve this info?


Solution

  • Your query does actually return the correct data. I tested this myself.

    A full example response will be structured like this:

    {
      "data": [
        {
          "created_at": "2021-06-05T02:33:48.000Z",
          "lang": "en",
          "id": "1401004298738311168",
          "text": "All conspiracy. But watch for bad news on Apple.  Such a vulnerable stocktechnically for the biggest market cap @ $2.1T ( Thanks Jay). This is the glue for the bulls. But, they stopped innovating when Steve died, built a fancy office and split the stock. $appl",
          "author_id": "1251347502013521925",
          "referenced_tweets": [
            {
              "type": "retweeted",
              "id": "1401004298738311168"
            }
          ]
        }
      ],
      "includes": {
        "users": [
          {
            "name": "Gary Casper",
            "id": "1251347502013521925",
            "username": "Hisel1979",
            "created_at": "2020-07-11T13:39:58.000Z"
          }
        ]
      }
    }
    

    The sample result you provided comes from within the data object. However, the expanded object data will be nested in the includes object (in your case name, username, and location). The corresponding user object can be referenced via the author_id field.