twitterapi.io is an independent third-party service. Not affiliated with X Corp.

Blogtwitter api python

Twitter (X) API with Python — Four Access Paths Compared

By Alex Chen7 min read

If you write Python and need Twitter (X) data, you have four practical choices in 2026: X's official XDK, the community Tweepy library, raw HTTPS with the requests library, or a third-party REST API such as twitterapi.io. The right pick depends almost entirely on cost per call, what you're authorized to do (read vs write), and how much library ergonomics matter for your specific code.

This guide walks through all four with runnable code, then compares them on five dimensions developers actually feel during integration: per-call cost, setup time, library ergonomics, write-operation support, and rate-limit headroom. The pricing numbers come straight from docs.x.com/x-api/getting-started/pricing and twitterapi.io/pricing (both verified June 2026) — the multipliers are simple division of the cited rates so you can re-derive them yourself.

01 — Section

Path 1 — X's official XDK (xdk on PyPI)

The XDK (X Developer Kit) is X's auto-generated official Python client. Install with pip install xdk, authenticate with a bearer token issued from the X Developer Console, and you get type hints, automatic pagination helpers, and streaming support. Because it tracks the docs.x.com OpenAPI spec exactly, new endpoints become available without waiting on community library updates.

The cost side maps directly to docs.x.com pricing: $0.005 per post read, $0.010 per user profile, $0.010 per following/follower fetch, $0.015 per post creation, $0.001 per owned-data read (your own posts/bookmarks). All reads deduplicate within a 24-hour UTC window — fetching the same post twice in the same day is billed once.

Pick XDK when you want the official path, plan to write (post / like / follow), and don't mind paying X's consumption rates. Skip it if your use case is read-heavy analytics where 33× cost per tweet matters more than first-class write support.

python
# pip install xdk
from xdk import XDK

client = XDK(bearer_token="YOUR_X_BEARER")

# Read a single post — billed $0.005 per resource, deduped per 24h UTC
post = client.posts.get(id="1234567890")
print(post.data.text)

# Paginated user lookup
for user in client.users.search(query="python", max_results=100):
    print(user.id, user.username)
02 — Section

Path 2 — Tweepy (the community standard)

Tweepy is the long-standing community library. It has more documentation surface area than XDK simply by being older — pip install tweepy works, and the Stack Overflow / GitHub issue trail is broad. Tweepy speaks the same docs.x.com endpoints and so is billed at the same X API rates.

The trade-offs are: (a) any post-Feb-2026 endpoint changes have to wait for a Tweepy release, whereas XDK regenerates from the spec; (b) Tweepy's v1.1 wrappers still exist in code samples scattered across the web, but the v1.1 endpoints are being progressively retired — confirm any tutorial you copy is targeting v2 (or the consumption-based v2026 surface) before relying on it.

Pick Tweepy if you have legacy code or you find Tweepy's Cursor pagination ergonomically nicer than XDK's iterators.

python
# pip install tweepy
import tweepy

client = tweepy.Client(bearer_token="YOUR_X_BEARER")

# Read a single post — billed $0.005 by X
resp = client.get_tweet(id="1234567890", tweet_fields=["created_at", "public_metrics"])
print(resp.data.text)

# Paginated user-timeline read using Paginator helper
for page in tweepy.Paginator(client.get_users_tweets, id="783214", max_results=100, limit=5):
    for t in page.data or []:
        print(t.id, t.text[:80])
03 — Section

Path 3 — Raw requests + bearer token (no library)

If you don't want a library dependency, the X API is just HTTPS with a bearer token. You lose pagination helpers and type hints, but you gain full control over headers, retries, and the exact JSON parsed. This path is the same docs.x.com surface and the same X API billing.

It's useful when you're embedding a single endpoint call into a larger system (a Lambda, a worker) and don't want to ship XDK or Tweepy as a dependency. It's painful when you actually need pagination and rate-limit handling — at that point a library pays for itself.

python
import os, requests

HEADERS = {"Authorization": f"Bearer {os.environ['X_BEARER']}"}

def get_post(post_id: str):
    r = requests.get(
        f"https://api.x.com/2/tweets/{post_id}",
        headers=HEADERS,
        params={"tweet.fields": "created_at,public_metrics"},
        timeout=10,
    )
    r.raise_for_status()
    return r.json()

print(get_post("1234567890"))
04 — Section

Path 4 — twitterapi.io REST API

twitterapi.io is a third-party REST gateway to the same data shape (tweets, profiles, followers, search, trends). No X Developer account, no bearer-token onboarding, no per-tier minimums — you sign up at twitterapi.io, get an API key, and call REST endpoints under the api.twitterapi.io host with that key in the X-API-Key header.

Per twitterapi.io/pricing (2026 verified): tweets are $0.00015 each (15 credits at 1 USD = 100,000 credits), profiles $0.00018, followers/following $0.00001–$0.00003 each tiered by page size, follower IDs $0.00001–$0.00002 tiered. There is no monthly minimum and no free tier — you pay per call.

Pick twitterapi.io when reads dominate your workload — analytics dashboards, tracking guides, batch ETL, archive backfills. The cost ratio against docs.x.com rates (math from cited numbers): $0.005 / $0.00015 = 33.33× per tweet read, $0.010 / $0.00018 = 55.56× per profile read, $0.010 / $0.00001 = 1000× per follower at the 200-item bulk tier. Writes (creating posts, deleting, etc.) are not in twitterapi.io's surface — for those you still need XDK or Tweepy.

python
import os, requests

HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
BASE = "https://api.twitterapi.io"

def get_tweets(tweet_ids: list[str]):
    """GET /twitter/tweets — batch tweet lookup by IDs."""
    r = requests.get(
        f"{BASE}/twitter/tweets",
        headers=HEADERS,
        params={"tweet_ids": ",".join(tweet_ids)},
        timeout=10,
    )
    r.raise_for_status()
    return r.json()

def get_user(username: str):
    """GET /twitter/user/info — profile lookup by handle."""
    r = requests.get(
        f"{BASE}/twitter/user/info",
        headers=HEADERS,
        params={"userName": username},
        timeout=10,
    )
    r.raise_for_status()
    return r.json()

print(get_tweets(["1234567890"]))
print(get_user("elonmusk"))
05 — Section

Side-by-side comparison — 5 dimensions developers feel

Same job (read a post, fetch a profile, page through followers) across four paths. Numbers are derived from the cited rates; setup-time judgment is based on the official onboarding flow each provider documents.

DimensionXDKTweepyRaw requeststwitterapi.io
Per-tweet read$0.005$0.005$0.005$0.00015
Per-profile read$0.010$0.010$0.010$0.00018
Per-follower read (bulk tier)$0.010$0.010$0.010$0.00001
Post creation (write)$0.015$0.015$0.015not supported
OnboardingX Developer account + credit purchaseX Developer account + credit purchaseX Developer account + credit purchasesign up at twitterapi.io, no developer review
Library ergonomicstype hints, pagination, streamingmature, Cursor paginationnone (you write it)none (you write it)
Spec-currentalways (auto-generated)community-paced releasesalways (you read the docs)API-stable, twitterapi.io maintains parity
Best formixed read+write under X authlegacy + read+writeembedded single callsread-heavy + cost-sensitive

Three honest calls: (a) if you need write — XDK or Tweepy, you're paying X's writes either way; (b) if you need read at scale — twitterapi.io is the natural answer because the cost ratio compounds against you on volume; (c) if you need both — many teams use both, XDK for the post-create / delete / DM-paths and twitterapi.io for the read-heavy analytics layer.

The 33× framing in the headline math is a single-row instance. The bulk-tier follower price ratio (1000×) is what tips production workloads — pulling a 500K-account graph at X API rates is $5,000 of credits; at twitterapi.io's bulk tier the same graph is ~$5.

06 — Section

Rate limit + reliability notes

X API rate limits are tier-dependent and documented per endpoint at docs.x.com. The consumption-based 2026 model means you don't hit a hard per-15-minute wall on the same axis as the old v1.1 tier — but X still throttles bursty patterns, and a 429 means back off and retry with jitter.

twitterapi.io maintains its own rate limits documented at twitterapi.io/docs. For dev / prototype workloads the limit is rarely the binding constraint — the binding constraint is whatever the source surface (X) returns. Production users typically pair twitterapi.io with a retry-with-backoff wrapper that handles 429s and 5xx similarly.

Neither path eliminates the realities of working with social platform data — deleted posts disappear, suspended accounts return 404, and rate-limited windows happen. Treat rate-limit handling as a first-class concern in any client you ship, regardless of which path you pick.

07 — Section

Picking a path — the decision rule

Three questions that resolve almost every case:

1. Do you need to write (create posts, like, retweet, follow)? If yes → XDK (preferred for the official path) or Tweepy. twitterapi.io does not offer write endpoints. Raw requests works too but you lose helpers.

2. Are reads dominant (analytics, monitoring, backfills, dashboards)? If yes and your monthly call volume is 1,000+ tweets or 100+ profiles → twitterapi.io's cost ratio against docs.x.com rates compounds quickly. At 1,000 tweet reads/day the X bill is $5/day ($150/mo) versus $0.15/day ($4.50/mo) at twitterapi.io, derivable from the same cited rates.

3. Is your workload mixed? Many production teams run both paths — XDK for the write surface (post create, list management) and twitterapi.io for the read-heavy analytics surface. Cost per call dominates at volume; XDK ergonomics dominate at the write layer where call counts are smaller.

python
# Side-by-side: same job (read a public profile), two paths, two prices.
# Cite the two pricing pages inline; the ratio is just division.
import os, requests

X_BEARER = os.environ["X_BEARER"]               # docs.x.com pricing: profile = $0.010
TAPI_KEY  = os.environ["TWITTERAPI_IO_KEY"]      # twitterapi.io/pricing: profile = $0.00018

def profile_x(username: str):
    """Read profile via X official surface."""
    r = requests.get(
        f"https://api.x.com/2/users/by/username/{username}",
        headers={"Authorization": f"Bearer {X_BEARER}"},
        params={"user.fields": "public_metrics,description,verified"},
        timeout=10,
    )
    r.raise_for_status()
    return r.json()

def profile_twitterapi_io(username: str):
    """Read same profile via twitterapi.io — GET /twitter/user/info."""
    r = requests.get(
        "https://api.twitterapi.io/twitter/user/info",
        headers={"X-API-Key": TAPI_KEY},
        params={"userName": username},
        timeout=10,
    )
    r.raise_for_status()
    return r.json()

# Cost ratio (from cited pricing pages, math is transparent):
# $0.010 / $0.00018 = 55.56x cheaper per profile read at twitterapi.io.
# For 10k profile lookups/month:
#   X API:        10_000 * 0.010 = $100
#   twitterapi.io: 10_000 * 0.00018 = $1.80
# Bills are derivable; verify against the live pricing pages before committing.
08 — Questions

Questions readers ask

Is the old `python-twitter` library still maintained?

python-twitter (geduldig/TwitterAPI on GitHub) is community-maintained and works against the X surface, but XDK is the official path and Tweepy is the community standard with the largest documentation surface. If you're picking fresh in 2026, lead with XDK or Tweepy.

Can I get tweets without an X Developer account at all?

Yes — twitterapi.io exposes the same read surface with just a twitterapi.io account and an API key (X-API-Key header). You skip the X Developer review flow entirely. Writes (post creation, like, retweet) still require X auth via XDK or Tweepy.

How does X's 24-hour dedup window affect cost?

Per docs.x.com/x-api/getting-started/pricing, requesting the same resource (post, profile) twice in the same UTC day incurs one charge, not two. This matters if your code re-polls the same IDs. twitterapi.io does not dedup the same way — re-reads are re-billed; cache your own results if you re-poll.

Are streaming endpoints supported in Python?

XDK supports streaming. Tweepy supports it. twitterapi.io exposes endpoints for a streaming-style use case via its filtered surface — see twitterapi.io/docs for the current shape. Raw requests can hit streaming endpoints but you'll write the keep-alive and reconnection logic yourself.

Does the 33× figure include rate-limit headers or just per-call price?

It's per-call price math, $0.005 / $0.00015 = 33.33, both numbers cited inline from the source pricing pages. Rate-limit envelopes differ per provider and per endpoint; check docs.x.com/x-api/getting-started/pricing and twitterapi.io/docs for the current rate-limit shape and treat them as separate concerns from per-call price.

I need to post AND read at scale — can I split paths?

Yes, and many production teams do. XDK or Tweepy for the write surface (under X auth + X credits), twitterapi.io for the read-heavy analytics layer. The split is operationally clean because each path has its own credentials and metering.

09 — Further reading

Continue

Sources & further reading
More from this series
Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key
    Twitter (X) API in Python — Complete Guide | TwitterAPI.io