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

이 가이드는 애플리케이션에 User 조회 엔드포인트를 연동하는 데 필요한 핵심 개념을 다룹니다.

***

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

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

| Method                                                                                                                            | Best for        | Can access private metrics? |
| :-------------------------------------------------------------------------------------------------------------------------------- | :-------------- | :-------------------------- |
| [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) | 사용자 대상 애플리케이션   | 예 (승인된 사용자의 데이터)            |
| [OAuth 1.0a User Context](/ko/resources/fundamentals/authentication)                                                              | 레거시 통합          | 예 (승인된 사용자의 데이터)            |

<div id="app-only-authentication">
  ### App 전용 인증
</div>

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

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

  # 사용자 이름으로 사용자 조회
  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>

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

인증된 사용자 엔드포인트(`/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 사용자 액세스 토큰 사용
  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 사용자 액세스 토큰 사용
  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>

***

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

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

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

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

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

<Accordion title="user.fields">
  | Field               | Description       |
  | :------------------ | :---------------- |
  | `created_at`        | 계정이 생성된 타임스탬프     |
  | `description`       | 사용자 소개            |
  | `entities`          | 소개에 포함된 URL 파싱 결과 |
  | `location`          | 사용자가 지정한 위치       |
  | `pinned_tweet_id`   | 고정된 게시물 ID        |
  | `profile_image_url` | 프로필 이미지 URL       |
  | `protected`         | 계정이 보호 계정인지 여부    |
  | `public_metrics`    | 팔로워/팔로잉 수         |
  | `url`               | 웹사이트 URL          |
  | `verified`          | 인증 상태             |
  | `withheld`          | 차단/보류 정보          |
</Accordion>

<Accordion title="tweet.fields (pinned_tweet_id 확장 필요)">
  | Field            | Description    |
  | :--------------- | :------------- |
  | `created_at`     | 게시물이 생성된 타임스탬프 |
  | `text`           | 게시물 내용         |
  | `public_metrics` | 참여 수치          |
  | `entities`       | 해시태그, 멘션, URL  |
</Accordion>

<div id="example-with-fields">
  ### 필드를 포함한 예제
</div>

<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 Python SDK 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)  # 확장된 고정 트윗이 포함됩니다
  ```

  ```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", {
    userFields: ["created_at", "description", "public_metrics", "verified"],
    expansions: ["pinned_tweet_id"],
    tweetFields: ["created_at", "public_metrics"],
  });

  console.log(response.data);
  console.log(response.includes); // 확장된 고정 트윗이 포함됩니다
  ```
</CodeGroup>

<div id="response-with-expansions">
  ### expansions를 포함한 응답
</div>

```json 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="필드 및 Expansions 가이드" icon="sliders" href="/ko/x-api/fundamentals/fields">
  응답을 커스터마이징하는 방법을 자세히 알아보세요
</Card>

***

<div id="batch-lookups">
  ## 배치 조회
</div>

하나의 요청으로 여러 사용자를 조회할 수 있습니다:

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

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

  ```python Python SDK 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 JavaScript SDK 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>

***

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

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

| Status | 오류        | 해결 방법                    |
| :----- | :-------- | :----------------------- |
| 400    | 잘못된 요청    | 매개변수 형식을 확인하세요           |
| 401    | 인증되지 않음   | 인증 정보를 확인하세요             |
| 403    | 접근이 거부됨   | App 권한을 확인하세요            |
| 404    | 찾을 수 없음   | 사용자가 존재하지 않거나 정지되었습니다    |
| 429    | 요청이 너무 많음 | 대기 후 다시 시도하세요 (요청 한도 참조) |

<div id="suspended-or-deleted-users">
  ### 정지되었거나 삭제된 사용자
</div>

사용자가 정지되었거나 삭제된 경우:

* 단일 사용자 조회는 `404`를 반환합니다
* 다중 사용자 조회에서는 결과에서 해당 사용자가 제외되며 `errors` 배열이 포함됩니다

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

<div id="protected-users">
  ### 보호된 사용자
</div>

팔로우하지 않는 보호된 계정의 경우:

* 기본 정보(id, name, username)는 확인할 수 있습니다
* 보호된 콘텐츠(고정된 게시물)에 대한 액세스는 제한될 수 있습니다
* `protected: true`는 계정의 상태를 나타냅니다

***

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

<CardGroup cols={2}>
  <Card title="일괄 요청" icon="layer-group">
    다중 사용자 엔드포인트를 사용해 한 번에 최대 100명의 사용자를 가져와 API 호출 횟수를 줄이세요.
  </Card>

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

  <Card title="사용자 데이터 캐싱" icon="database">
    반복 요청을 줄이기 위해 사용자 프로필을 로컬에 캐싱하세요.
  </Card>

  <Card title="오류를 우아하게 처리" icon="triangle-exclamation">
    일괄 응답에서 일부 오류가 있는지 확인하세요.
  </Card>
</CardGroup>

***

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

<CardGroup cols={2}>
  <Card title="API 참조 문서" icon="code" href="/ko/x-api/users/get-user-by-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>
