Twitter (X) API with Python — Four Access Paths Compared
- 4 access paths: XDK (official, ergonomic), Tweepy (community, mature), raw requests (no library), twitterapi.io (REST, no X Developer account needed)
- X API pricing (docs.x.com/x-api/getting-started/pricing, 2026 verified): post read $0.005, profile read $0.010, follower/following read $0.010, post creation $0.015, owned reads $0.001 — 24h UTC dedup window
- twitterapi.io pricing (twitterapi.io/pricing, 2026 verified): tweet $0.00015, profile $0.00018, follower IDs $0.0000045–$0.00002 — ratio is 33×–1000× cheaper on bulk reads, derivable math
- Pick by use case: read-heavy analytics → twitterapi.io; write/post-creation flows → XDK or Tweepy with X credits, or twitterapi.io's v2 write endpoints through your own account session; mixed → one of each
If you write Python and need Twitter (X) data (the classic "python twitter api" question), 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-result 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 in 2026) — the multipliers are simple division of the cited rates so you can re-derive them yourself.
$0.005 vs $0.00015 — 33× cheaper (derivable from cited pricing pages)
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.
# 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)
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.
# 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])
Tweepy example: resolve a handle, then read the timeline
A detail that trips people up: in Tweepy v4, Client.get_user takes keyword-only arguments, client.get_user(*, id=None, username=None, user_fields=None, ...). Pass exactly one of id or username by name. client.get_user("nasa") raises a TypeError because the positional slot does not exist, and passing both id and username is rejected too. Resolve a handle with get_user(username=...), then use the numeric user.data.id for timeline calls such as get_users_tweets.
With wait_on_rate_limit=True, Tweepy sleeps through a rate-limit window instead of raising. Each response's .data holds the parsed results and .meta carries the pagination token:
import tweepy
client = tweepy.Client(bearer_token="YOUR_BEARER_TOKEN",
wait_on_rate_limit=True)
# Resolve the handle to a numeric id, then pull recent posts
user = client.get_user(username="nasa")
resp = client.get_users_tweets(user.data.id, max_results=10)
for tweet in resp.data or []:
print(tweet.text)
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. For a complete scheduled version on AWS, see Twitter API on AWS Lambda with EventBridge and SQS, which deploys a poller and a worker with one SAM template.
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"))
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. Every call carries the key in one header; our X-API-Key header guide shows the exact curl, requests and fetch syntax and what 401 vs 403 mean. The same key and endpoints work from PHP with one Guzzle client; see our Twitter API in PHP guide.
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.0000045–$0.00002 tiered. There is no monthly minimum: new accounts get free starter credits (bot check, one per person, expires after 31 days), and after that you pay-per-result.
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 = about 33× per tweet read, $0.010 / $0.00018 = about 55× 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.
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"))
Authentication: OAuth vs an API key
This is the sharpest practical difference between the two paths.
Official API: OAuth. For read-only access you generate an OAuth 2.0 app-only Bearer Token in the developer portal; for write actions you need the fuller OAuth 1.0a user-context flow with consumer keys and access tokens. tweepy manages the tokens once you have created them, but creating an app and getting approved is a real first step. Our guide to X bearer tokens and access tokens explains the four credential types, which endpoints need which, and how to check that a token works.
Third-party API: a single header. You send X-API-Key: <your key> with each request and that is the whole of it — no token exchange, no app review, no callback URLs.
For a script whose job is to read public data, the API-key model removes an entire category of setup work and an entire category of bugs.

The core read operations
Four operations cover the large majority of what Python scripts do with Twitter data:
Fetch a user's posts — GET /twitter/user/last_tweets with a userName. Returns recent posts with full engagement counts. The basis of timeline analysis and competitor tracking.
Search — GET /twitter/tweet/advanced_search with a query (the operator language) and a queryType of Latest or Top. The basis of brand monitoring and topic collection.
Walk the follower graph — the follower and following endpoints, paginated, to reconstruct who follows whom. The basis of network and audience analysis.
Look up a profile — GET /twitter/user/info with a userName, for the follower count, verification and bio of any public account.
Each returns documented JSON, so the Python side is just a dict access — no scraping, no HTML parsing.
Pagination: the cursor loop
A single request returns one page. To collect more than a page you loop on a cursor.
The third-party endpoints return a page of results plus a has_next_page boolean and a next_cursor string. The loop is: make the request, append the results, and if has_next_page is true, pass next_cursor back as a parameter on the next call — stop when it is false.
Always cap the loop with a maximum-results guard. Because billing is per result, an unbounded loop on a broad query is the easiest way to spend more than you meant to. The guarded version:
import requests
# Third-party API (TwitterAPI.io): no OAuth, single header, pay-per-result.
API_KEY = "your_api_key_here" # in real code: os.environ["TWITTER_API_KEY"]
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": API_KEY}
def get_latest_tweets(username, max_count=20):
"""Fetch a user's latest posts, paging on the cursor up to max_count."""
out, cursor = [], ""
while len(out) < max_count:
params = {"userName": username}
if cursor:
params["cursor"] = cursor
r = requests.get(
f"{BASE}/twitter/user/last_tweets",
params=params,
headers=HEADERS,
timeout=30,
)
r.raise_for_status()
body = r.json()
out.extend(body["data"]["tweets"])
if not body["has_next_page"]:
break
cursor = body["next_cursor"]
return out[:max_count]
def search_tweets(query, query_type="Latest"):
"""Run an advanced-search query. query_type: 'Latest' or 'Top'."""
r = requests.get(
f"{BASE}/twitter/tweet/advanced_search",
params={"query": query, "queryType": query_type},
headers=HEADERS,
timeout=30,
)
r.raise_for_status()
return r.json()["tweets"]
if __name__ == "__main__":
for t in get_latest_tweets("nasa", max_count=10):
print(f"{t['createdAt']}: {t['text'][:100]}")
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.
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.
Rate limit + reliability notes
X API rate limits are 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 stop returning profile data (twitterapi.io flags them in the response body with data.unavailable, not with an HTTP error), 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.
The retry pattern that works is exponential backoff on an HTTP 429: wait one second and retry, then two, then four, capping the wait so a stuck loop does not sleep forever. With tweepy this is built in; with requests, implement it yourself or wrap the call with the tenacity library, which makes retry-with-backoff a one-line decorator.
Either way, never retry tightly in a bare loop — an un-backed-off retry storm just burns your rate budget faster.
What people build with Python and Twitter data
The Python-plus-Twitter combination clusters around a few projects:
Bulk collection — run the cursor loop over a list of accounts or a search query and write each post into SQLite or a CSV via pandas. The non-obvious part is deduplication: key the store on tweet id so re-runs and overlapping queries do not double-count.
Network and audience graphs — walk follower and following lists into an edge list, load it into networkx to find communities, or simply rank followers by account size and last-active date to separate a real audience from dormant accounts.
Sentiment and brand monitoring — search brand mentions and score each post with a sentiment library: vaderSentiment for speed, a Hugging Face transformers pipeline for accuracy. Aggregate the scores by day for a brand-health line.
Analytics and charting — load the collected posts into a pandas DataFrame, resample by a time bucket, and plot with matplotlib or plotly — engagement curves, volume over time, an hour-of-day heatmap.
For the step-by-step version of the collection workflow (search, paginate, load into pandas, save to CSV), see how to get Twitter (X) data in Python.
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; raw requests works too but you lose helpers. twitterapi.io has write endpoints as well, called with plain requests; the next paragraph says how they work.
Write actions on twitterapi.io run through an authenticated session: you log the account in once with POST /twitter/user_login_v2 ($0.10), passing a proxy you supply, then each post, delete, like, retweet, follow or unfollow is $0.0006. The call acts as that account, so X's rules apply to it and X can rate-limit, lock or suspend it; keep a human pace. The session can require a new login, the proxy is required on every write call, and billing is per successful call; refusals from X (status: error) are not charged. Read endpoints need only an API key and no X account. Against the official rate card: $0.015 per post on the official API (Post: Create) vs $0.0006 here (0.015 / 0.0006 = 25x), and $0.015 per like, follow or retweet (User Interaction: Create) vs $0.0006 here. The official side is cheaper for a single action on a fresh login, because the $0.10 login is extra ($0.015 there vs $0.0006 + $0.10 = $0.1006 here; it is one login per session, not per action), and the gap is smallest on a deleted post: $0.005 on X (Content: Manage) vs $0.0006 here.
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.
# 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 = about 55x 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.Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
What's the easiest way to use the Twitter API in Python?
For reading public data, a third-party API called with the requests library — there is no SDK to learn (a twitterapi-io package exists if you prefer one), no OAuth flow, and you authenticate with a single header. For writing to Twitter or accessing official-only data, the tweepy library against the official X API is the standard choice, at the cost of a developer account and OAuth setup.
Is tweepy still the right library for the Twitter API?
tweepy remains the established Python wrapper for the official X API and is the right tool when you are committed to that API — typically for write access or official-only data. It does not help with third-party APIs, though; for those you use plain requests, which needs no wrapper at all.
Do I need OAuth for Python Twitter API access?
For the official API, yes — an OAuth 2.0 app-only Bearer Token for reads, or the fuller OAuth 1.0a user-context flow for writes. For a third-party API, no — authentication is a single X-API-Key header with no token exchange.
How do I paginate Twitter API results in Python?
Loop on a cursor. The endpoints return a page plus a has_next_page flag and a next_cursor string; request a page, append it, and if the flag is true pass the cursor back on the next call. Always cap the loop with a maximum-results guard, since billing is per result.
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-result 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-result 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. twitterapi.io's own write endpoints (see the decision rule above) make a single-provider stack possible too.
Continue
- X API — pricing (docs.x.com, 2026 verified)
- twitterapi.io — pricing
- Tweepy documentation
- xdk on PyPI (X official Python SDK)
- Get Twitter (X) data in Python: search, paginate, pandas and CSV
- Twitter (X) API — full cluster hub
- X API cost breakdown 2026 — full per-endpoint table
- Migrating from Tweepy to twitterapi.io — guided rewrite
- twitterapi.io pricing
- Twitter API in PHP guide
- X-API-Key header guide
- Twitter API on AWS Lambda with EventBridge and SQS
- Twitter (X) bearer token and access token guide
- 01B2B on Twitter (X) in 2026: Is It Worth It, and What Actually Works
- 02Twitter (X) Lead Generation: Finding and Qualifying Buyers with Search
- 03Twitter (X) Influencer Marketing: Find and Vet Creators With Data
- 04Twitter (X) and MongoDB: store tweets as documents, upsert by id, query them fast
- 05Supabase + Twitter (X) API: store tweets in Postgres with an Edge Function and pg_cron
- 06Twitter (X) Trends API in Python — Three Paths, One Tutorial
- 07Tweepy vs TwitterAPI.io
- 08Get Twitter (X) Data in Python (2026 Tutorial)
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.