> ## 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.

# 統合ガイド

> このガイドでは、Post lookup エンドポイントをアプリケーションに統合する際に必要な主要概念を扱います。lookup を扱う X API v2 スタンダードティアのリファレンス。

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>;
};

このガイドでは、Post lookup エンドポイントをアプリケーションに統合する際に必要な主要概念を扱います。

***

## 認証

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

| Method                                                                                                                         | Best for    | Can access private metrics? |
| :----------------------------------------------------------------------------------------------------------------------------- | :---------- | :-------------------------- |
| [OAuth 2.0 App-Only](/resources/fundamentals/authentication#oauth-2-0)                                                         | サーバー間、公開データ | No                          |
| [OAuth 2.0 Authorization Code with PKCE](/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | ユーザー向けアプリ   | Yes(認可済みユーザーの投稿)            |
| [OAuth 1.0a User Context](/resources/fundamentals/authentication)                                                              | 従来の統合       | Yes(認可済みユーザーの投稿)            |

### App-Only 認証

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

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

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

  client = Client(bearer_token="YOUR_BEARER_TOKEN")

  # ID で単一の投稿を取得
  response = client.posts.get("1234567890")
  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.posts.get("1234567890");
  console.log(response.data);
  ```
</CodeGroup>

### User Context 認証

非公開メトリクスにアクセスするには、投稿の作成者の代理で認証します:

<Warning>
  以下のフィールドは User Context 認証が必要です:

  * `tweet.fields.non_public_metrics`
  * `tweet.fields.promoted_metrics`
  * `tweet.fields.organic_metrics`
  * `media.fields.non_public_metrics`
  * `media.fields.promoted_metrics`
  * `media.fields.organic_metrics`
</Warning>

***

## Fields と expansions

X API v2 はデフォルトで最小限のデータを返します。`fields` と `expansions` を使って必要なものだけをリクエストします。

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

```json theme={null}
{
  "data": {
    "id": "1234567890",
    "text": "Hello world!",
    "edit_history_tweet_ids": ["1234567890"]
  }
}
```

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

<Accordion title="tweet.fields">
  | Field                 | Description              |
  | :-------------------- | :----------------------- |
  | `created_at`          | 投稿作成タイムスタンプ              |
  | `author_id`           | 作成者のユーザー ID              |
  | `public_metrics`      | いいね、リツイート、返信、引用数         |
  | `entities`            | ハッシュタグ、メンション、URL、キャッシュタグ |
  | `attachments`         | メディアキー、poll ID           |
  | `conversation_id`     | スレッド識別子                  |
  | `context_annotations` | トピック/エンティティ分類            |
  | `in_reply_to_user_id` | 返信先のユーザー                 |
  | `lang`                | 検出された言語                  |
  | `source`              | 投稿クライアント                 |
  | `possibly_sensitive`  | センシティブコンテンツフラグ           |
  | `reply_settings`      | 誰が返信できるか                 |
</Accordion>

<Accordion title="user.fields(author_id expansion が必要)">
  | Field               | Description   |
  | :------------------ | :------------ |
  | `username`          | @ハンドル         |
  | `name`              | 表示名           |
  | `profile_image_url` | アバター URL      |
  | `verified`          | 認証ステータス       |
  | `description`       | 自己紹介          |
  | `public_metrics`    | フォロワー / フォロー数 |
  | `created_at`        | アカウント作成日      |
</Accordion>

<Accordion title="media.fields(attachments.media_keys expansion が必要)">
  | Field               | Description               |
  | :------------------ | :------------------------ |
  | `url`               | メディア URL                  |
  | `preview_image_url` | サムネイル URL                 |
  | `type`              | photo、video、animated\_gif |
  | `duration_ms`       | 動画の再生時間                   |
  | `height`, `width`   | サイズ                       |
  | `alt_text`          | アクセシビリティテキスト              |
</Accordion>

### フィールド付きの例

<CodeGroup dropdown>
  ```bash cURL theme={null}
  curl "https://api.x.com/2/tweets/1234567890?\
  tweet.fields=created_at,public_metrics,entities&\
  expansions=author_id,attachments.media_keys&\
  user.fields=username,verified&\
  media.fields=url,type" \
    -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.posts.get(
      "1234567890",
      tweet_fields=["created_at", "public_metrics", "entities"],
      expansions=["author_id", "attachments.media_keys"],
      user_fields=["username", "verified"],
      media_fields=["url", "type"]
  )

  print(response.data)
  print(response.includes)  # 展開された user と media オブジェクトを含む
  ```

  ```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.posts.get("1234567890", {
    tweetFields: ["created_at", "public_metrics", "entities"],
    expansions: ["author_id", "attachments.media_keys"],
    userFields: ["username", "verified"],
    mediaFields: ["url", "type"],
  });

  console.log(response.data);
  console.log(response.includes); // 展開された user と media オブジェクトを含む
  ```
</CodeGroup>

***

## 投稿の編集

投稿は作成から 30 分以内に最大 5 回まで編集できます。

### しくみ

* 各編集は新しい投稿 ID を作成します
* `edit_history_tweet_ids` にはすべてのバージョンが古い順に含まれます
* エンドポイントは常に最新バージョンを返します

### レスポンス例

```json theme={null}
{
  "data": {
    "id": "1234567893",
    "text": "Hello world! (edited twice)",
    "edit_history_tweet_ids": [
      "1234567890",
      "1234567891",
      "1234567893"
    ]
  }
}
```

<Tip>
  30 分の編集期間経過後に取得した投稿は最終バージョンを表します。リアルタイムユースケースでは、公開直後の投稿がまだ編集される可能性があることに注意してください。
</Tip>

***

## エラー処理

### 一般的なエラー

| Status | Error             | Solution          |
| :----- | :---------------- | :---------------- |
| 400    | 無効なリクエスト          | パラメーターの形式を確認      |
| 401    | Unauthorized      | 認証情報を検証           |
| 403    | Forbidden         | App の権限を確認        |
| 404    | Not Found         | 投稿が削除されたか存在しない    |
| 429    | Too Many Requests | 待機してリトライ(レート制限参照) |

### 削除済みまたは保護された投稿

投稿が削除されているか、フォローしていない保護アカウントの投稿の場合:

* 単一投稿の lookup は `404` を返します
* 複数投稿の lookup では結果からその投稿が省略され、`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": "1234567890", "text": "Available post" }
  ],
  "errors": [
    {
      "resource_id": "1234567891",
      "resource_type": "tweet",
      "title": "Not Found Error",
      "detail": "Could not find tweet with id: [1234567891]."
    }
  ]
}
```

***

## ベストプラクティス

<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/szd6PKNMlRQoyyAo/icons/xds/icon-history.svg?fit=max&auto=format&n=szd6PKNMlRQoyyAo&q=85&s=6afe17587c08ee621e37afde19a07ff1" width="24" height="24" data-path="icons/xds/icon-history.svg">
    リアルタイムアプリでは、30 分の編集期間後に投稿を再取得することを検討してください。
  </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/posts/post-lookup-by-post-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>
