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

# 연동 가이드

> 게시물 조회 연동을 위한 핵심 개념과 모범 사례

export const Button = ({href, children}) => {
  return <div className="not-prose group">
    <a href={href}>
      <button className="flex items-center space-x-2.5 py-1 px-4 bg-primary-dark dark:bg-white text-white dark:text-gray-950 rounded-full group-hover:opacity-[0.9] font-medium">
        <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>;
};

이 가이드에서는 애플리케이션에 게시물 조회 엔드포인트를 통합하는 데 필요한 핵심 개념을 다룹니다.

***

<div id="authentication">
  ## 인증
</div>

모든 X API v2 엔드포인트는 인증이 필요합니다. 사용 사례에 가장 잘 맞는 방식을 선택하세요:

| 방식                                                                                                                                | 최적 용도           | 비공개 메트릭에 접근 가능 여부 |
| :-------------------------------------------------------------------------------------------------------------------------------- | :-------------- | :---------------- |
| [OAuth 2.0 App-Only](/ko/resources/fundamentals/authentication#oauth-2-0)                                                         | 서버 간 통신, 공개 데이터 | 아니요               |
| [OAuth 2.0 Authorization Code with PKCE](/ko/resources/fundamentals/authentication#oauth-2-0-authorization-code-flow-with-pkce-2) | 사용자 대상 App      | 예 (인가된 사용자의 포스트)  |
| [OAuth 1.0a User Context](/ko/resources/fundamentals/authentication)                                                              | 레거시 통합          | 예 (인가된 사용자의 포스트)  |

<div id="app-only-authentication">
  ### App-Only authentication
</div>

공개 게시물 데이터를 조회할 때는 Bearer 토큰을 사용합니다:

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

<div id="user-context-authentication">
  ### User Context 인증
</div>

비공개 메트릭에 접근하려면 게시물 작성자를 대신하여 인증해야 합니다.

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

***

<div id="fields-and-expansions">
  ## 필드와 expansions
</div>

X API v2는 기본적으로 최소한의 데이터만 반환합니다. 정확히 필요한 데이터만 요청하려면 `fields`와 `expansions`를 사용하세요.

<div id="default-response">
  ### 기본 응답
</div>

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

<div id="available-fields">
  ### 사용 가능한 필드
</div>

<Accordion title="tweet.fields">
  | Field                 | Description          |
  | :-------------------- | :------------------- |
  | `created_at`          | 게시물 생성 타임스탬프         |
  | `author_id`           | 작성자의 사용자 ID          |
  | `public_metrics`      | 좋아요, 리포스트, 답글, 인용 횟수 |
  | `entities`            | 해시태그, 멘션, URL, 캐시태그  |
  | `attachments`         | 미디어 키, 투표 ID         |
  | `conversation_id`     | 스레드 식별자              |
  | `context_annotations` | 토픽/엔터티 분류            |
  | `in_reply_to_user_id` | 답글 대상 사용자            |
  | `lang`                | 감지된 언어               |
  | `source`              | 게시 클라이언트             |
  | `possibly_sensitive`  | 민감한 콘텐츠 플래그          |
  | `reply_settings`      | 답글 허용 범위             |
</Accordion>

<Accordion title="user.fields (requires author_id expansion)">
  | Field               | Description |
  | :------------------ | :---------- |
  | `username`          | @핸들         |
  | `name`              | 표시 이름       |
  | `profile_image_url` | 아바타 URL     |
  | `verified`          | 인증 상태       |
  | `description`       | 소개(바이오)     |
  | `public_metrics`    | 팔로워/팔로잉 수   |
  | `created_at`        | 계정 생성 날짜    |
</Accordion>

<Accordion title="media.fields (requires attachments.media_keys expansion)">
  | Field               | Description                 |
  | :------------------ | :-------------------------- |
  | `url`               | 미디어 URL                     |
  | `preview_image_url` | 썸네일 URL                     |
  | `type`              | photo, video, animated\_gif |
  | `duration_ms`       | 동영상 길이                      |
  | `height`, `width`   | 크기                          |
  | `alt_text`          | 접근성 텍스트                     |
</Accordion>

<div id="example-with-fields">
  ### 필드가 포함된 예시
</div>

<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 Python SDK 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)  # 확장된 사용자 및 미디어 객체를 포함
  ```

  ```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", {
    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); // 확장된 사용자 및 미디어 객체를 포함
  ```
</CodeGroup>

***

<div id="post-edits">
  ## 게시물 수정
</div>

게시물은 작성 후 30분 이내에 최대 5번까지 수정할 수 있습니다.

<div id="how-it-works">
  ### 작동 방식
</div>

* 각 편집 시 새로운 게시물 ID가 생성됩니다
* `edit_history_tweet_ids`에는 모든 버전이 포함되며, 가장 오래된 것부터 나열됩니다
* 이 엔드포인트에서는 항상 최신 버전을 반환합니다

<div id="example-response">
  ### 응답 예시
</div>

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

<Tip>
  30분짜리 편집 가능 시간이 지난 뒤에 조회된 포스트는 최종 버전입니다. 실시간 사용 사례에서는 최근에 게시된 포스트가 아직 수정 중일 수 있다는 점에 유의하세요.
</Tip>

***

<div id="error-handling">
  ## 오류 처리
</div>

<div id="common-errors">
  ### 일반적인 오류
</div>

| Status | Error       | Solution                     |
| :----- | :---------- | :--------------------------- |
| 400    | 잘못된 요청      | 매개변수 형식을 확인하세요               |
| 401    | 인증 실패       | 인증 정보를 확인하세요                 |
| 403    | 액세스 거부      | App 권한을 확인하세요                |
| 404    | 찾을 수 없음     | 게시물이 삭제되었거나 존재하지 않습니다        |
| 429    | 요청이 너무 많습니다 | 잠시 기다렸다가 다시 시도하세요 (요청 한도 참고) |

<div id="deleted-or-protected-posts">
  ### 삭제되었거나 보호된 포스트
</div>

게시물이 삭제되었거나, 사용자가 팔로우하지 않는 보호된 계정의 게시물인 경우:

* 단일 게시물 조회에서는 `404`를 반환합니다.
* 다중 게시물 조회에서는 결과에서 해당 게시물을 제외하고 `errors` 배열을 포함합니다.

```json 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]."
    }
  ]
}
```

***

<div id="best-practices">
  ## 모범 사례
</div>

<CardGroup cols={2}>
  <Card title="요청 일괄 처리" icon="layer-group">
    multi-Post endpoint를 사용해 한 번에 최대 100개의 게시물을 가져와 API 호출을 줄이세요.
  </Card>

  <Card title="필요한 필드만 요청" icon="filter">
    응답 크기와 처리 시간을 최소화하기 위해 필요한 필드만 지정하세요.
  </Card>

  <Card title="응답 캐싱" icon="database">
    동일한 콘텐츠에 대한 반복 요청을 줄이기 위해 게시물 데이터를 로컬에 캐싱하세요.
  </Card>

  <Card title="수정 처리" icon="clock-rotate-left">
    실시간 앱의 경우 30분 편집 가능 시간이 지난 후에 게시물을 다시 조회하는 것을 고려하세요.
  </Card>
</CardGroup>

***

<div id="next-steps">
  ## 다음 단계
</div>

<CardGroup cols={2}>
  <Card title="API 참조 문서" icon="code" href="/ko/x-api/posts/post-lookup-by-post-id">
    완전한 엔드포인트 문서
  </Card>

  <Card title="데이터 사전" icon="book" href="/ko/x-api/fundamentals/data-dictionary">
    사용 가능한 모든 객체와 필드
  </Card>

  <Card title="샘플 코드" icon="github" href="https://github.com/xdevplatform/Twitter-API-v2-sample-code">
    동작하는 코드 예제
  </Card>

  <Card title="오류 처리" icon="triangle-exclamation" href="/ko/x-api/fundamentals/response-codes-and-errors">
    오류를 안정적으로 처리하는 방법
  </Card>
</CardGroup>
