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

# 페이지네이션

> 대규모 결과 집합을 탐색합니다

API 응답에 한 번에 반환할 수 있는 것보다 더 많은 결과가 포함된 경우, 페이지네이션을 사용하여 모든 페이지의 데이터를 가져올 수 있습니다.

***

<div id="how-pagination-works">
  ## 페이지네이션의 동작 방식
</div>

1. 초기 요청을 `max_results`와 함께 보냅니다.
2. 응답의 `meta` 객체에 `next_token`이 있는지 확인합니다.
3. 있다면 해당 토큰을 `pagination_token`으로 사용해 다시 요청을 보냅니다.
4. `next_token`이 더 이상 반환되지 않을 때까지 반복합니다.

```bash theme={null}
# 초기 요청
curl "https://api.x.com/2/users/12345/tweets?max_results=100" \
  -H "Authorization: Bearer $TOKEN"

# 응답에 next_token 포함됨
# {"data": [...], "meta": {"next_token": "abc123", ...}}

# 다음 페이지
curl "https://api.x.com/2/users/12345/tweets?max_results=100&pagination_token=abc123" \
  -H "Authorization: Bearer $TOKEN"
```

***

<div id="pagination-tokens">
  ## 페이지네이션 토큰
</div>

| Token              | 설명                                                      |
| :----------------- | :------------------------------------------------------ |
| `next_token`       | 응답의 `meta`에 포함됩니다. 다음 페이지를 가져오는 데 사용합니다.                |
| `previous_token`   | 응답의 `meta`에 포함됩니다. 이전 페이지로 이동하는 데 사용합니다.                |
| `pagination_token` | 요청 매개변수입니다. `next_token` 또는 `previous_token` 값으로 설정합니다. |

***

<div id="response-structure">
  ## 응답 구조
</div>

```json theme={null}
{
  "data": [
    {"id": "1234", "text": "..."},
    {"id": "1235", "text": "..."}
  ],
  "meta": {
    "result_count": 100,
    "next_token": "7140w9gefhslx3",
    "previous_token": "77qp89slxjd"
  }
}
```

더 이상 반환할 결과가 없으면 `next_token`이 포함되지 않습니다:

```json theme={null}
{
  "data": [...],
  "meta": {
    "result_count": 42,
    "previous_token": "77qp89abc"
  }
}
```

***

<div id="pagination-parameters">
  ## 페이지네이션 매개변수
</div>

| 매개변수               | 설명             | 기본값       |
| :----------------- | :------------- | :-------- |
| `max_results`      | 페이지당 결과 수      | 엔드포인트별 상이 |
| `pagination_token` | 이전 응답에서 제공된 토큰 | 없음        |

각 엔드포인트의 API 참조 문서에서 `max_results`에 대한 구체적인 제한 값을 확인하세요.

***

<div id="example-paginating-through-all-results">
  ## 예시: 모든 결과를 페이지네이션하기
</div>

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import requests

    def get_all_tweets(user_id, bearer_token):
        url = f"https://api.x.com/2/users/{user_id}/tweets"
        headers = {"Authorization": f"Bearer {bearer_token}"}
        params = {"max_results": 100}
        
        all_tweets = []
        
        while True:
            response = requests.get(url, headers=headers, params=params)
            data = response.json()
            
            if "data" in data:
                all_tweets.extend(data["data"])
            
            # 다음 페이지가 있는지 확인
            next_token = data.get("meta", {}).get("next_token")
            if not next_token:
                break
                
            params["pagination_token"] = next_token
        
        return all_tweets
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    async function getAllTweets(userId, bearerToken) {
      const url = `https://api.x.com/2/users/${userId}/tweets`;
      const headers = { Authorization: `Bearer ${bearerToken}` };
      
      let allTweets = [];
      let paginationToken = null;
      
      do {
        const params = new URLSearchParams({ max_results: 100 });
        if (paginationToken) {
          params.set("pagination_token", paginationToken);
        }
        
        const response = await fetch(`${url}?${params}`, { headers });
        const data = await response.json();
        
        if (data.data) {
          allTweets.push(...data.data);
        }
        
        paginationToken = data.meta?.next_token;
      } while (paginationToken);
      
      return allTweets;
    }
    ```
  </Tab>
</Tabs>

***

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

<CardGroup cols={2}>
  <Card title="max_results 사용" icon="arrow-up-1-9">
    API 호출을 최소화하려면 허용되는 최대값인 `max_results`를 요청하세요.
  </Card>

  <Card title="부분 페이지 처리" icon="square-check">
    마지막 페이지에는 `max_results`보다 적은 결과만 있을 수 있습니다.
  </Card>

  <Card title="토큰 저장" icon="database">
    나중에 페이지네이션을 다시 시작해야 하는 경우를 대비해 `next_token`을 저장하세요.
  </Card>

  <Card title="페이지네이션으로 폴링하지 마세요" icon="clock">
    새 데이터를 가져올 때는 페이지네이션을 반복해서 실행하는 대신 `since_id`를 사용하세요.
  </Card>
</CardGroup>

***

<div id="result-ordering">
  ## 결과 정렬
</div>

결과는 **시간 역순(최신순)** 으로 반환됩니다.

* 첫 페이지의 첫 번째 결과 = 가장 최근 결과
* 마지막 페이지의 마지막 결과 = 가장 오래된 결과

이 규칙은 페이지 내부와 페이지 간 모두에 적용됩니다.

***

<div id="notes">
  ## 참고 사항
</div>

* 페이지네이션 토큰은 불투명한 문자열입니다. 파싱하거나 수정하지 마세요.
* 토큰은 일정 시간이 지나면 만료될 수 있습니다.
* `max_results`보다 적은 결과를 받은 경우에도 더 많은 결과가 존재할 수 있습니다. (`next_token`이 더 이상 제공되지 않을 때까지 계속 요청)
* 자동 페이지네이션 처리를 위해 [SDK](/ko/x-api/tools-and-libraries/sdks)를 사용하세요.

***

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

<CardGroup cols={2}>
  <Card title="요청 한도" icon="gauge-high" href="/ko/x-api/fundamentals/rate-limits">
    페이지네이션을 사용할 때 적용되는 요청 한도를 이해하세요.
  </Card>

  <Card title="SDKs" icon="cube" href="/ko/x-api/tools-and-libraries/sdks">
    페이지네이션 기능이 내장된 라이브러리를 사용하세요.
  </Card>
</CardGroup>
