TwexAPI で X ユーザープロフィールを一括取得する方法
X の handle がすでにある場合、次に必要になるのはプロフィール補完です。elonmusk、sundarpichai、または profile URL の列を、CRM、調査データベース、ダッシュボードで使える構造化された profile レコードに変えます。
TwexAPI の Get Multiple Users エンドポイントは、この用途に使えます。ユーザー名または X profile URL の配列を POST /twitter/users に送り、返ってきたユーザーオブジェクトを正規化し、見つからなかったアカウントも明確に記録します。
このエンドポイントを使う場面
入力が handle または profile URL のリストで、プロフィールメタデータを一括取得したいときは POST /twitter/users を使います。
代表的な用途は次の通りです。
- インフルエンサー表に、名前、bio、所在地、認証フィールド、レスポンスに含まれるフォロワー数を追加する。
- キャンペーン前に KOL データベースを更新する。
- コミュニティリスト内の handle が現在も有効な profile に解決できるか確認する。
- ツイート、返信、List、検索結果から集めたデータに作者メタデータを追加する。
入力がユーザー名ではなく数値の user ID の場合は、POST /twitter/users/by_ids を使います。
エンドポイントとリクエスト本文
POST リクエストを次の URL に送ります。
https://api.twexapi.io/twitter/usersリクエスト本文は文字列の JSON 配列です。各文字列には、ユーザー名または profile URL を指定できます。
curl --request POST \
--url https://api.twexapi.io/twitter/users \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '[
"elonmusk",
"sundarpichai",
"https://x.com/tim_cook"
]'API は code、msg、data を含むオブジェクトを返します。data 配列にはユーザープロフィールオブジェクトが入ります。ユーザー名が見つからない場合、その位置が null になることがあるため、コード側で明示的に処理してください。
1{
2 "code": 200,
3 "msg": "success",
4 "data": [
5 {
6 "userId": "44196397",
7 "username": "elonmusk",
8 "name": "Elon Musk",
9 "description": "<profile bio>",
10 "followersCount": 1000000,
11 "isBlueVerified": true,
12 "verified": true
13 },
14 null
15 ]
16}レスポンスのフィールド名は固定のデータベース schema として扱わず、まず raw profile を保存し、その後でプロダクトに必要なフィールドをマッピングするのが安全です。
Python 一括補完スクリプト
次のスクリプトは handle のリストを読み、POST /twitter/users をバッチで呼び出し、正規化した JSONL を書き出し、見つからなかった入力を記録します。
1import json
2import time
3from datetime import datetime, timezone
4from pathlib import Path
5
6import requests
7
8TOKEN = "<your_bearer_token>"
9URL = "https://api.twexapi.io/twitter/users"
10INPUTS = [
11 "elonmusk",
12 "sundarpichai",
13 "https://x.com/tim_cook",
14]
15BATCH_SIZE = 20
16OUT = Path("x-user-profiles.jsonl")
17MISSING = Path("x-user-profiles-missing.json")
18
19headers = {
20 "Authorization": f"Bearer {TOKEN}",
21 "Content-Type": "application/json",
22}
23
24def chunks(items, size):
25 for index in range(0, len(items), size):
26 yield items[index:index + size]
27
28missing = []
29
30with OUT.open("w", encoding="utf-8") as f:
31 for batch in chunks(INPUTS, BATCH_SIZE):
32 response = requests.post(URL, headers=headers, json=batch, timeout=30)
33 response.raise_for_status()
34 body = response.json()
35 profiles = body.get("data") or []
36
37 for original_input, profile in zip(batch, profiles):
38 if profile is None:
39 missing.append(original_input)
40 continue
41
42 row = {
43 "input": original_input,
44 "user_id": profile.get("userId") or profile.get("user_id"),
45 "username": profile.get("username") or profile.get("screen_name"),
46 "name": profile.get("name"),
47 "description": profile.get("description"),
48 "followers_count": profile.get("followersCount") or profile.get("followers_count"),
49 "verified": profile.get("verified"),
50 "is_blue_verified": profile.get("isBlueVerified") or profile.get("is_blue_verified"),
51 "fetched_at": datetime.now(timezone.utc).isoformat(),
52 "raw": profile,
53 }
54 f.write(json.dumps(row, ensure_ascii=False) + "\n")
55
56 time.sleep(1)
57
58MISSING.write_text(json.dumps({
59 "fetched_at": datetime.now(timezone.utc).isoformat(),
60 "missing": missing,
61}, ensure_ascii=False, indent=2), encoding="utf-8")
62
63print(f"Saved profiles to {OUT}; missing inputs: {len(missing)}")バッチサイズはプランとエラー許容度に合わせて決めます。小さいバッチはリトライしやすく、どの入力が失敗したかも追いやすくなります。
見つからないアカウントや改名への対応
一括 profile 補完では、handle の変更、アカウント停止、余計なパラメータ付きの profile URL などがよく混ざります。lookup の過程を追跡できるようにします。
- 元の入力と、API が返した正規化済みユーザー名を一緒に保存する。
null結果は黙って捨てず、別の missing ファイルに保存する。- missing アカウントは後で再確認してから、恒久的に利用不可と判断する。
- 大文字小文字をそろえ、URL 接頭辞を外してから重複排除する。
- profile メタデータは変わるため、取得時刻を保存する。
これにより、出力をプロダクトでも後の監査でも使いやすくできます。
User ID がある場合
元データに数値の user ID がすでにある場合は、次を呼び出します。
POST https://api.twexapi.io/twitter/users/by_idsリクエスト本文は同じく文字列配列ですが、各要素は user ID です。
curl --request POST \
--url https://api.twexapi.io/twitter/users/by_ids \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '[
"44196397",
"1696160451770429440"
]'すでに user ID がある場合は、長期的な join には ID が向いています。入力がスプレッドシート、profile URL、インフルエンサーリスト、手作業の調査から来る場合は、ユーザー名のほうが扱いやすいです。
データパイプラインでの位置づけ
きれいな profile enrichment パイプラインは、通常 4 段階です。
- 検索、List メンバー、ツイート作者、返信、スプレッドシートから候補 handle を集める。
- handle を正規化し、重複を取り除く。
POST /twitter/usersをバッチで呼び出し、raw response を保存する。- アプリケーションに必要なフィールドを安定したテーブルにマッピングする。
分析では、フォロワー数だけでランキングを決めないほうが安全です。アウトリーチや予算に関わる判断では、最近の投稿、エンゲージメントの質、トピック適合、手動確認を組み合わせます。
まとめ
ユーザー名ベースのプロフィール補完には、handle または profile URL の JSON 配列を POST /twitter/users に送ります。raw profile を保存し、null 結果を処理し、元入力と正規化後の profile を並べて残します。
これで、ばらばらな X handle リストを使いやすい profile テーブルに変えられます。同時に、profile データが永遠に安定しているかのように扱うリスクも避けられます。