Get Tweets by Username in Python: Resolve the Handle, Then Page next_cursor

Published October 12, 2026 · UpdatedOctober 16, 2026

A spreadsheet of public handles looks like a search problem: drop NASA into query, pin search_type=Latest, and treat every hit as that account's posts. Search is not this account's timeline. search matches text. A documented query=NASA also returned lowercase "nasa" from unrelated authors writing in other languages. Matching the brand word does not establish authorship. user-timeline is scoped to one public account. Its next_cursor is not a search cursor, and a handle sitting in a spreadsheet is not a user id until user-info says so.

This guide is one Python loop: resolve the handle, refuse notfound, page next_cursor on the same account, keep tweet ids as strings. Opening this page or copying the script does not send a request. A call happens only when you replace the placeholders and run it, and each deliberate request may consume credits.

The X (Twitter) Public Data API is an independent, read-only GET surface. It is not the official X API, not Tweepy, and not a complete archive or a stream. Public counters are collection-time snapshots.

Sign in, copy an authorized key from the dashboard, and keep it in OPENDATA_API_KEY on the server. Snippets that show YOUR_API_KEY are dead placeholders, not live credentials. The key travels on the query string, so those URLs do not belong in tickets, screenshots, browser history, or frontend bundles. No X password, cookie, or session is involved.

Search is not this account's timeline

Search takes required query. Optional search_type=Latest is the verified mode; other modes are not established here. Continuation uses that operation's own next_cursor for the same query and the same mode. Hits carry tweet_id, text, screen_name, and user_info. Check user_info.rest_id before you assign account identity. Brand-mention queues belong on search. An authored-post dataset does not.

If you paste a search cursor into user-timeline, you are mixing two ledgers. The gateway will not translate a keyword page into an account page. If you skip resolution and treat NASA as a numeric id, you never confirmed the account exists, and you never received rest_id as a string. Handles change. rest_id does not.

users-media is a media-bearing account timeline, still keyed by screenname, not by a keyword. followers and following page people, not posts; their cursors are another ledger. tweet-info looks up one string id. None of those substitute for user-timeline when the job is this account's recent posts.

Keep the query and capture time on any search export, then filter relevance downstream. Do not rename a search JSONL to nasa_timeline.jsonl because the query string matched the handle.

Resolve the handle, then page next_cursor

user-info requires screenname without @. The documented public example is NASA. Optional rest_id overrides account selection but does not drop the schema-required handle — you still send screenname. On a hit, status is active and the payload includes rest_id. Store that id as a string before any timeline call.

Every response has two status layers. HTTP 4xx/5xx is transport, auth, or quota: the call did not run. HTTP 200 is not success by itself. The gateway envelope is {code, message, data}, and business success is code=200. Only then read the operation payload in data. Gateway success with status=notfound is a miss, not an empty timeline. Inspect failures through redacted code and message; a full URL in a stack trace leaks the key.

First user-timeline request: screenname, plus the resolved rest_id if you keep selection pinned. Omit cursor. Do not send an empty string to hold the slot. The observed payload has status=ok, timeline, user, next_cursor, and prev_cursor. Feed next_cursor back unchanged as cursor on the same account. Stop on a missing, empty, whitespace-only, or repeated cursor. Page size is whatever timeline actually contains — an observation, not a contract. Reaching a stop is not a complete history.

Install requests and export the key privately. The loop below is a local page budget (PAGE_BUDGET = 5), not a published service limit or retry contract. It writes x_timeline.jsonl only when you execute it.

import json
import os
from datetime import datetime, timezone

import requests

BASE = "https://api.opendata-api.com/api/project/twitter"
API_KEY = os.environ["OPENDATA_API_KEY"]
HANDLE = "NASA"
PAGE_BUDGET = 5  # Local cost guard, not an API limit.


def get(operation, **params):
    try:
        response = requests.get(
            f"{BASE}/{operation}",
            params={"key": API_KEY, **params},
            timeout=(10, 30),
        )
    except requests.RequestException:
        raise RuntimeError("Request failed; retry later") from None
    if not 200 <= response.status_code < 300:
        raise RuntimeError(f"HTTP {response.status_code}")
    try:
        envelope = response.json()
    except ValueError:
        raise RuntimeError("Expected JSON") from None
    if not isinstance(envelope, dict) or envelope.get("code") != 200:
        raise RuntimeError("Gateway business failure; inspect sanitized status")
    data = envelope.get("data")
    if not isinstance(data, dict):
        raise RuntimeError("Unexpected endpoint payload")
    return data


def utc_timestamp(value):
    if not isinstance(value, str):
        return None
    try:
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
    except ValueError:
        parsed = datetime.strptime(value, "%a %b %d %H:%M:%S %z %Y")
    if parsed.tzinfo is None:
        raise ValueError("Timestamp needs an explicit timezone")
    return parsed.astimezone(timezone.utc).isoformat()


def counter(value):
    return int(value) if value is not None and str(value).isdigit() else None


profile = get("user-info", screenname=HANDLE)
if profile.get("status") == "notfound":
    raise SystemExit("Public handle not found; correct it before collecting")
if profile.get("status") != "active" or not profile.get("rest_id"):
    raise RuntimeError("Unresolved account status or ID")
target_id = str(profile["rest_id"])
seen_ids, seen_cursors = set(), set()
cursor, skipped = None, 0

with open("x_timeline.jsonl", "w", encoding="utf-8") as output:
    for _ in range(PAGE_BUDGET):
        params = {"screenname": HANDLE, "rest_id": target_id}
        if cursor:
            params["cursor"] = cursor
        page = get("user-timeline", **params)
        if page.get("status") != "ok" or not isinstance(page.get("timeline"), list):
            raise RuntimeError("Unexpected timeline status or records")
        collected_at = datetime.now(timezone.utc).isoformat()
        for post in page["timeline"]:
            if not isinstance(post, dict) or not post.get("tweet_id"):
                raise RuntimeError("Invalid post record")
            author = post.get("author") or {}
            if not isinstance(author, dict) or str(author.get("rest_id")) != target_id:
                skipped += 1
                continue
            tweet_id = str(post["tweet_id"])
            if tweet_id in seen_ids:
                continue
            post["tweet_id"], author["rest_id"] = tweet_id, target_id
            row = {
                "collected_at": collected_at,
                "target_id": target_id,
                "created_at_utc": utc_timestamp(post.get("created_at")),
                "metrics": {
                    k: counter(post.get(k))
                    for k in (
                        "favorites",
                        "retweets",
                        "replies",
                        "quotes",
                        "bookmarks",
                        "views",
                    )
                },
                "post": post,
            }
            output.write(json.dumps(row, ensure_ascii=False) + "\n")
            seen_ids.add(tweet_id)
        next_cursor = page.get("next_cursor")
        if next_cursor is None or next_cursor == "":
            break
        if not isinstance(next_cursor, str):
            raise RuntimeError("Unexpected cursor type")
        if not next_cursor.strip() or next_cursor in seen_cursors:
            break
        seen_cursors.add(next_cursor)
        cursor = next_cursor

print("Saved posts:", len(seen_ids), "unassigned records:", skipped)

Optional rest_id on later pages still does not remove screenname. For handle-only selection, omit rest_id and still verify returned author.rest_id. Treat the cursor as opaque: do not parse it, increment it, or reuse a search, media, or follower cursor. Adjacent pages can overlap, which is why string tweet_id deduplication lives in the same loop.

Bound retries to transport failures. Do not retry notfound. Do not loop until the archive feels complete — available history varies, and each page spends credits. Check current pricing if you need consumption numbers.

Keep tweet ids as strings

X identifiers sit outside JavaScript's safe integer range. If a JSON parser turns tweet_id or rest_id into a number, converting that number back to a string cannot recover lost digits. Keep them as text in Python, in the JSONL, and in the database column. The script above forces str(...) before the set membership test for that reason.

Deduplicate with the string id across pages in one run. Persist (target_id, tweet_id) if you poll again later; an in-memory set dies with the process. This demonstration overwrites its file.

Timeline likes are favorites. tweet-info uses likes for the same public idea. views can be a numeric string. Missing or null counters stay missing — substituting zero invents activity. Stamp collected_at on every row; counters move between runs, so the snapshot time is part of the record. The helper tries ISO-8601 and a Twitter-style date, and rejects unknown formats or missing timezones instead of guessing. Keep raw created_at next to normalized UTC.

Reposts may include retweeted and retweeted_tweet. Author details may be null. Count unassigned rows separately instead of attributing them to the resolved account. An authors-only export is narrower than all account activity; if you study amplification, keep the repost context and validate it separately.

If you need one post refreshed — display text, media, a later counter snapshot — call tweet-info with required string id after the loop, on an id you already collected. Do not fire it once per row inside the page budget. Inspect that operation's business status before reading author, media, or likes. Unavailable-post behavior is not established here.

notfound is not an empty timeline

A verified missing handle returned status=notfound with null identity and null counters. That is not an active account with zero tweets. Do not insert those nulls as zero followers. Do not start user-timeline on that handle. Do not retry the same input as if the profile were flaky. Correct the handle, or park the row as unavailable.

A timeline status other than ok, or a timeline that is not a list, is unexpected structure — stop parsing rather than rewriting it as empty success. An empty timeline array on an active profile can be a quiet window; it is still not notfound. Protected accounts are out of scope for this public collector: if protected is true, skip the feed instead of paging until something leaks.

Coverage notes belong on the export: the handle you sent, the rest_id you resolved, the captured window, the page budget, and why you stopped. Do not label the file a complete archive. Process public data lawfully, and do not treat returned media URLs as republication rights.

The mistakes that still show up after the script compiles: searching the handle and calling the hits a timeline; pasting a search next_cursor into user-timeline; treating the handle as a user id without user-info; sending page=2 or incrementing the cursor; dropping required screenname because you already have rest_id; storing tweet_id as a number; treating notfound as zero activity; treating HTTP 200 as a hit; retrying a miss; enriching every row with tweet-info inside the loop; logging request URLs that still contain the key.

See user-timeline, user-info, search, and tweet-info. Per-request cost is on pricing.