> ## 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 엔드포인트를 통합할 때 필요한 핵심 개념을 다룹니다. Lookup을 다루는 X API v2 standard 티어 레퍼런스입니다.

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

***

## 필드 및 확장

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`       | 사용자 소개       |
  | `entities`          | 소개에서 파싱된 URL |
  | `location`          | 사용자가 설정한 위치  |
  | `pinned_tweet_id`   | 고정된 Post ID  |
  | `profile_image_url` | 아바타 URL      |
  | `protected`         | 비공개 계정 여부    |
  | `public_metrics`    | 팔로워/팔로잉 수    |
  | `url`               | 웹사이트 URL     |
  | `verified`          | 인증 상태        |
  | `withheld`          | 보류 정보        |
</Accordion>

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

### fields를 사용한 예시

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

  # 추가 필드 및 expansion과 함께 사용자 가져오기
  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)  # 확장된 고정 tweet 포함
  ```

  ```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); // 확장된 고정 tweet 포함
  ```
</CodeGroup>

### expansion이 포함된 응답

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

***

## 배치 조회

단일 요청으로 여러 사용자 조회:

<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 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 | 잠시 후 재시도 (rate limit 참조) |

### 정지되거나 삭제된 사용자

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

* 단일 사용자 조회는 `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>
