LoginSignup
2
1

More than 1 year has passed since last update.

TwitterAPI v2でuser_fieldsの項目が取得できていないように見えても、実は取得できているから大丈夫

Posted at

結論

user_fieldsのようなオプショナルな項目は、単にオブジェクト全体をprintしただけでは文字列として表現されないようになっているらしい。
ちゃんと明示的にアクセスすれば取り出せる。

params = {
    'id' : 1526881736214597632,
    'user_fields' : 'public_metrics'
}
res = client.get_user(**params)
# ID: 1526881736214597632の総ツイート数を知りたかったので、public_metricsを要求

print(res.data)
# => <User id=1526881736214597632 name=壱百満天原サロメ💯🦂 username=1000000lome>
# user_fieldsやpublic_metricsが出てこないので、一見すると含まれていないように見える

print(res.data.public_metrics)
# => {'followers_count': 564575,
#     'following_count': 1,
#     'listed_count': 4033,
#     'tweet_count': 182}
# ちゃんと個別の項目を指定するとアクセスできる

環境

  • Python 3.9
  • tweepy

経緯

レスポンスデータを単純にprintして
user_fieldsを指定したのに入ってないじゃないか😡
と怒っていたところ、以下のStackOverflowの記事に救われた。

Unable to retrieve public metrics using tweepy.Client

曰く、TwitterAPI v2のFAQに書いてあるよとのこと。

Why am I not getting expansions or fields data with API v2 using Client?

If you are simply printing the objects and looking at that output, the string representations of API v2 models/objects only include the default attributes that are guaranteed to exist.

The objects themselves still include the relevant data, which you can access as attributes or by key, like a dictionary.

[Google翻訳]
クライアントを使用してAPIv2で拡張またはフィールドデータを取得できないのはなぜですか?

オブジェクトを印刷してその出力を確認するだけの場合、API v2モデル/オブジェクトの文字列表現には、存在が保証されているデフォルトの属性のみが含まれます。

オブジェクト自体には、属性として、または辞書のようにキーでアクセスできる関連データが含まれています。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1