> ## Documentation Index
> Fetch the complete documentation index at: https://docs.x.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 連携ガイド

> このガイドでは、User lookup エンドポイントをアプリケーションに連携するために必要な主要概念を説明します。X API v2 スタンダード階層の lookup に関するリファレンスドキュメントです。

export const Button = ({href, children}) => {
  return <div className="not-prose">
    <a href={href}>
      <button className="x-btn">
        <span>{children}</span>
        <svg width="3" height="24" viewBox="0 -9 3 24" class="h-6 rotate-0 overflow-visible"><path d="M0 0L3 3L0 6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></path></svg>
      </button>
    </a>
  </div>;
};

このガイドでは、User lookup エンドポイントをアプリケーションに連携するために必要な主要概念を説明します。

***

## 認証

すべての X API v2 エンドポイントには認証が必要です。ユースケースに合った方式を選択してください:

| Method                                                                                                                         | Best for      | プライベートなメトリクスにアクセスできるか |
| :----------------------------------------------------------------------------------------------------------------------------- | :------------ | :-------------------- |
| [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0)                                                         | サーバー間通信、公開データ | 不可                    |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | ユーザー向けアプリ     | 可 (認可済みユーザーのデータについて)  |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication)                                                              | レガシー連携        | 可 (認可済みユーザーのデータについて)  |

### App-Only 認証

公開ユーザーデータには Bearer Token を使用します:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/users/by/username/XDevelopers" \
    -H "Authorization: Bearer $BEARER_TOKEN"
  ```

  ```python Python SDK theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_BEARER_TOKEN")

  # username でユーザーを取得
  response = client.users.get_by_username("XDevelopers")
  print(response.data)
  ```

  ```javascript JavaScript SDK theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });

  const response = await client.users.getByUsername("XDevelopers");
  console.log(response.data);
  ```
</CodeGroup>

### User Context 認証

認証済みユーザーエンドポイント (`/2/users/me`) では必須です:

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/users/me" \
    -H "Authorization: Bearer $USER_ACCESS_TOKEN"
  ```

  ```python Python SDK theme={null}
  from xdk import Client

  # OAuth 2.0 ユーザー access token を使用
  client = Client(bearer_token="YOUR_USER_ACCESS_TOKEN")

  # 認証済みユーザーのプロフィールを取得
  response = client.users.get_me()
  print(response.data)
  ```

  ```javascript JavaScript SDK theme={null}
  import { Client } from "@xdevplatform/xdk";

  // OAuth 2.0 ユーザー access token を使用
  const client = new Client({ accessToken: "YOUR_USER_ACCESS_TOKEN" });

  const response = await client.users.getMe();
  console.log(response.data);
  ```
</CodeGroup>

<Warning>
  `/2/users/me` エンドポイントは User Context 認証でのみ動作します。App-Only トークンではエラーが返ります。
</Warning>

***

## Fields と expansions

X API v2 はデフォルトでは最小限のデータのみを返します。必要なデータを正確にリクエストするには `fields` と `expansions` を使用します。

### デフォルトのレスポンス

```json theme={null}
{
  "data": {
    "id": "2244994945",
    "name": "X Developers",
    "username": "XDevelopers"
  }
}
```

### 利用可能なフィールド

<Accordion title="user.fields">
  | Field               | Description      |
  | :------------------ | :--------------- |
  | `created_at`        | アカウント作成のタイムスタンプ  |
  | `description`       | ユーザーの bio        |
  | `entities`          | bio 内のパース済み URL  |
  | `location`          | ユーザーが設定した所在地     |
  | `pinned_tweet_id`   | ピン留めした Post の ID |
  | `profile_image_url` | アバターの URL        |
  | `protected`         | アカウントが非公開かどうか    |
  | `public_metrics`    | フォロワー/フォロー中の件数   |
  | `url`               | Web サイトの URL     |
  | `verified`          | 認証済みステータス        |
  | `withheld`          | 保留情報             |
</Accordion>

<Accordion title="tweet.fields (pinned_tweet_id expansion が必要)">
  | Field            | Description      |
  | :--------------- | :--------------- |
  | `created_at`     | Post 作成のタイムスタンプ  |
  | `text`           | Post の本文         |
  | `public_metrics` | エンゲージメントの件数      |
  | `entities`       | ハッシュタグ、メンション、URL |
</Accordion>

### フィールドを使った例

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/users/by/username/XDevelopers?\
  user.fields=created_at,description,public_metrics,verified&\
  expansions=pinned_tweet_id&\
  tweet.fields=created_at,public_metrics" \
    -H "Authorization: Bearer $BEARER_TOKEN"
  ```

  ```python title="Python SDK" lines wrap icon="python" theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_BEARER_TOKEN")

  # 追加フィールドと expansions 付きでユーザーを取得
  response = client.users.get_by_username(
      "XDevelopers",
      user_fields=["created_at", "description", "public_metrics", "verified"],
      expansions=["pinned_tweet_id"],
      tweet_fields=["created_at", "public_metrics"]
  )

  print(response.data)
  print(response.includes)  # 展開されたピン留め Post が含まれます
  ```

  ```javascript title="JavaScript SDK" lines wrap icon="square-js" theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });

  const response = await client.users.getByUsername("XDevelopers", {
    userFields: ["created_at", "description", "public_metrics", "verified"],
    expansions: ["pinned_tweet_id"],
    tweetFields: ["created_at", "public_metrics"],
  });

  console.log(response.data);
  console.log(response.includes); // 展開されたピン留め Post が含まれます
  ```
</CodeGroup>

### expansions 付きのレスポンス

```json title="レスポンス例" lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data": {
    "id": "2244994945",
    "name": "X Developers",
    "username": "XDevelopers",
    "created_at": "2013-12-14T04:35:55.000Z",
    "verified": true,
    "pinned_tweet_id": "1234567890",
    "public_metrics": {
      "followers_count": 583423,
      "following_count": 2048,
      "tweet_count": 14052
    }
  },
  "includes": {
    "tweets": [
      {
        "id": "1234567890",
        "text": "Welcome to the X Developer Platform!",
        "created_at": "2024-01-15T10:00:00.000Z"
      }
    ]
  }
}
```

<Card title="Fields と expansions ガイド" icon="sliders" href="/x-api/fundamentals/fields">
  レスポンスのカスタマイズについて詳しく学ぶ
</Card>

***

## バッチルックアップ

1 度のリクエストで複数のユーザーをルックアップします:

<CodeGroup dropdown>
  ```bash cURL (by IDs) theme={null}
  curl "https://api.x.com/2/users?ids=2244994945,783214,6253282&\
  user.fields=username,verified" \
    -H "Authorization: Bearer $BEARER_TOKEN"
  ```

  ```bash cURL (by usernames) theme={null}
  curl "https://api.x.com/2/users/by?usernames=XDevelopers,X,XAPI&\
  user.fields=username,verified" \
    -H "Authorization: Bearer $BEARER_TOKEN"
  ```

  ```python title="Python SDK" lines wrap icon="python" theme={null}
  from xdk import Client

  client = Client(bearer_token="YOUR_BEARER_TOKEN")

  # ID で複数ユーザーを取得
  response = client.users.get_users(
      ids=["2244994945", "783214", "6253282"],
      user_fields=["username", "verified"]
  )
  for user in response.data:
      print(f"{user.username}: {user.verified}")

  # username で複数ユーザーを取得
  response = client.users.get_users_by_usernames(
      usernames=["XDevelopers", "X", "XAPI"],
      user_fields=["username", "verified"]
  )
  for user in response.data:
      print(f"{user.username}: {user.verified}")
  ```

  ```javascript title="JavaScript SDK" lines wrap icon="square-js" theme={null}
  import { Client } from "@xdevplatform/xdk";

  const client = new Client({ bearerToken: "YOUR_BEARER_TOKEN" });

  // ID で複数ユーザーを取得
  const byIds = await client.users.getUsers({
    ids: ["2244994945", "783214", "6253282"],
    userFields: ["username", "verified"],
  });
  byIds.data.forEach((user) => {
    console.log(`${user.username}: ${user.verified}`);
  });

  // username で複数ユーザーを取得
  const byUsernames = await client.users.getUsersByUsernames({
    usernames: ["XDevelopers", "X", "XAPI"],
    userFields: ["username", "verified"],
  });
  byUsernames.data.forEach((user) => {
    console.log(`${user.username}: ${user.verified}`);
  });
  ```
</CodeGroup>

<Tip>
  バッチリクエストは最大 100 ユーザーに制限されます。より大きなデータセットには複数リクエストを利用してください。
</Tip>

***

## エラー処理

### 一般的なエラー

| Status | Error             | Solution             |
| :----- | :---------------- | :------------------- |
| 400    | Invalid request   | パラメータの書式を確認          |
| 401    | Unauthorized      | 認証情報を確認              |
| 403    | Forbidden         | App の権限を確認           |
| 404    | Not Found         | ユーザーが存在しないか凍結されている   |
| 429    | Too Many Requests | 待機してから再試行 (レート制限を参照) |

### 凍結・削除されたユーザー

ユーザーが凍結または削除されている場合:

* 単一ユーザーのルックアップでは `404` が返る
* 複数ユーザーのルックアップでは、そのユーザーは結果から除外され `errors` 配列に含まれる

```json title="レスポンス例" lines wrap icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-brackets.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=ed2428e77bab43e57800e1a590e982fa" theme={null}
{
  "data": [
    { "id": "2244994945", "username": "XDevelopers" }
  ],
  "errors": [
    {
      "resource_id": "1234567890",
      "resource_type": "user",
      "title": "Not Found Error",
      "detail": "Could not find user with id: [1234567890]."
    }
  ]
}
```

### 非公開ユーザー

フォローしていない非公開アカウントについて:

* 基本情報 (id、name、username) は取得可能
* 非公開のコンテンツ (ピン留めした Post) は制限される場合があります
* `protected: true` はアカウントのステータスを示します

***

## ベストプラクティス

<CardGroup cols={2}>
  <Card title="バッチリクエスト" icon="layer-group">
    マルチユーザーエンドポイントで一度に最大 100 ユーザーを取得し、API 呼び出し回数を減らします。
  </Card>

  <Card title="必要なフィールドのみリクエスト" icon="https://mintcdn.com/x-preview/szd6PKNMlRQoyyAo/icons/xds/icon-filter.svg?fit=max&auto=format&n=szd6PKNMlRQoyyAo&q=85&s=5d59aff402c1f2aeae0e9e44bb23400e" width="24" height="24" data-path="icons/xds/icon-filter.svg">
    必要なフィールドのみを指定してレスポンスサイズを最小化します。
  </Card>

  <Card title="ユーザーデータをキャッシュ" icon="database">
    ユーザープロフィールをローカルにキャッシュし、繰り返しリクエストを減らします。
  </Card>

  <Card title="エラーを丁寧に処理" icon="https://mintcdn.com/x-preview/jLbdFJYHCS9a6gmb/icons/xds/icon-warning.svg?fit=max&auto=format&n=jLbdFJYHCS9a6gmb&q=85&s=3760ceda7c43e1ffbd9f8b7ccbf83cca" width="24" height="24" data-path="icons/xds/icon-warning.svg">
    バッチレスポンスの部分的なエラーを確認します。
  </Card>
</CardGroup>

***

## 次のステップ

<CardGroup cols={2}>
  <Card title="API リファレンス" icon="https://mintcdn.com/x-preview/ygI6sSJPehlc0qNT/icons/xds/icon-code.svg?fit=max&auto=format&n=ygI6sSJPehlc0qNT&q=85&s=488e23401b19225b89acc0136d242219" href="/x-api/users/get-user-by-id" width="24" height="24" data-path="icons/xds/icon-code.svg">
    エンドポイントの詳細ドキュメント
  </Card>

  <Card title="データディクショナリ" icon="https://mintcdn.com/x-preview/Vn2KEkZaPF9LiPi3/icons/xds/icon-book.svg?fit=max&auto=format&n=Vn2KEkZaPF9LiPi3&q=85&s=22ac564792481d14ae36a941546039c8" href="/x-api/fundamentals/data-dictionary" width="24" height="24" data-path="icons/xds/icon-book.svg">
    利用可能なオブジェクトとフィールドすべて
  </Card>

  <Card title="サンプルコード" icon="github" href="https://github.com/xdevplatform/Twitter-API-v2-sample-code">
    動作するコード例
  </Card>

  <Card title="エラー処理" icon="https://mintcdn.com/x-preview/jLbdFJYHCS9a6gmb/icons/xds/icon-warning.svg?fit=max&auto=format&n=jLbdFJYHCS9a6gmb&q=85&s=3760ceda7c43e1ffbd9f8b7ccbf83cca" href="/x-api/fundamentals/response-codes-and-errors" width="24" height="24" data-path="icons/xds/icon-warning.svg">
    エラーを丁寧に処理する
  </Card>
</CardGroup>
