X API v2 recent-search pagination: handling pages that exactly match max_results
0 reputation · 08 Jan 2023, 01:32 UTC
0 reputation · 08 Jan 2023, 01:32 UTC
When paginating the recent‑search endpoint (/2/tweets/search/recent) with a fixed max_results value, a client receives a meta.next_token only when additional pages are available. The specification does not state whether a response that returns exactly max_results items must always include a next_token when more results remain, leaving the boundary case ambiguous.
Furthermore, the documentation does not guarantee how long a pagination_token remains valid; a token may expire after an unspecified interval, causing subsequent requests to fail with an error that resembles a data problem.
Does a response that returns exactly max_results items guarantee the presence of a next_token when more results exist? If not, how should a client determine whether to continue pagination? What is the guaranteed validity duration of a pagination_token, and what error indicates expiration?
33275 reputation · 08 Jan 2023, 09:41 UTC
No. A page that returns exactly max_results items does not guarantee the presence of meta.next_token. If the matching dataset happens to end exactly on a page boundary, the final page can be full and still have no next_token. The only authoritative signal that more pages exist is the presence of meta.next_token in the response — never the item count.
The common logic error is writing a loop like while len(items) == max_results. That condition is wrong in both directions:
The correct loop is token-driven:
token = None
while True:
resp = search_recent(query, max_results=100, next_token=token)
yield resp["data"]
token = resp.get("meta", {}).get("next_token")
if not token:
breakWhen next_token is absent, pagination is complete — regardless of how many items the last page contained.
X does not publish a guaranteed validity duration for pagination_token values. Treat them as short-lived, opaque cursors tied to your exact query state, not permanent pointers. Practical implications:
max_results (e.g., 10) against a high-volume term. Confirm meta.next_token appears while more results exist.max_results (or approximate it by paging to the end) and observe that the last full page arrives without a next_token.This reflects well-established v2 pagination behavior as generally documented and observed, but X's API terms and endpoint behavior change periodically. Confirm against the current developer documentation for your access tier, and treat the token-lifetime question as environment-specific until you've measured it yourself.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.