How to Get Tweets with Python in 2026 (3 Ways)
How to get tweets with Python in 2026: what the official X API costs, why scraping libraries break, and working code to search, page and save to CSV.
You can get tweets with Python in three ways: the official X API, a scraping library, or a hosted REST API called with requests.
This guide is for developers who need X (Twitter) posts in a script or a CSV. You get what each route costs and how fragile it is, then working code for the third. We run Weir, the API in the examples, so weigh our view knowing that.
Paste this to see your first posts:
import os, requests
r = requests.post(
"https://api.weirapp.io/v1/x/search",
headers={"Authorization": f"Bearer {os.environ['WEIR_API_KEY']}"},
json={"query": "python", "language": "en", "limit": 20},
timeout=60,
)
for post in r.json()["data"]:
print(post["author"]["username"], post["text"][:80])
Here is the map of the tutorial:
- Get a keySign up, copy a key, set WEIR_API_KEY.
- Search postsPOST /v1/x/search with a query or filters.
- Read one accountGET /v1/x/users/{user}/posts.
- Page with the cursorSend meta.nextCursor back until it is null.
- Save to CSVWrite each post as a row with csv.DictWriter.
Three ways to get tweets with Python in 2026, with or without the X API
Each route trades money against reliability. Here they are side by side, as of October 2026:
| Route | You need | Cost to read posts | Main risk |
|---|---|---|---|
| Official X API | Developer account, credits | $0.005 per post | Cost at volume |
| twscrape, twikit | Your own X accounts | Free in money | Breaks without warning |
| Weir REST API | An API key | 1,050 credits per 1,000 | A third party, not X |
The rest of this section covers the first two. The steps after it use the third.
The official X API with Tweepy
X bills its API per use: you buy credits, and each post read costs $0.005. X's pricing page caps these plans at 3 million post reads a month.
The same post fetched twice in one UTC day is charged once.
Recent search covers the last 7 days, at up to 100 posts per request. Full-archive search goes back to 2006 and returns up to 500 per request.
Tweepy is the long-standing Python client, still maintained at version 4.17.0. A minimal recent search:
import os, tweepy
client = tweepy.Client(bearer_token=os.environ["X_BEARER_TOKEN"])
response = client.search_recent_tweets(
query="python lang:en -is:retweet",
max_results=100,
tweet_fields=["created_at", "public_metrics"],
)
for tweet in response.data or []:
print(tweet.id, tweet.public_metrics["like_count"])
X also publishes its own Python SDK, xdk, if you'd rather skip a community library.
The math is simple. A 100-post request costs 50 cents, so 10,000 posts cost $50. In return you get X's own terms, write access and the 500-post archive search.
The v2 API has its own query dialect. It rejects min_faves: with a 400 and wants min_likes: instead. Our X advanced search operators guide maps both dialects.
Scraping libraries: twscrape, twikit, snscrape
These libraries call the private endpoints x.com's web app uses. We checked their state on GitHub and PyPI on 19 October 2026:
- snscrape last shipped in June 2023. Its issue #996, "All Twitter scrapes are failing", is still open.
- twikit last shipped 2.3.3 in February 2025. Open issues include a KeyError since April 2026.
- twscrape is active, at 0.21.0 (6 November 2026). Its README says it "requires authorized X/Twitter accounts".
They share one weakness. When X changes an internal endpoint, they break until a maintainer catches up, and your accounts carry the risk.
X's Terms of Service also say you "cannot scrape the Services without X's express written permission". This isn't legal advice. Our twikit and twscrape alternatives guide goes deeper.
Step 1: Get a key and set up
Sign up with no card, create a key under API keys, then install requests:
pip install requests
export WEIR_API_KEY="weir_live_..."
One shared session keeps the auth header in one place:
import os, time, requests
API = "https://api.weirapp.io"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['WEIR_API_KEY']}"
Step 2: Search tweets with Python
Search is POST /v1/x/search with a JSON body. Write X's search syntax in query, or use fields like fromUsers, minLikes and since.
Weir turns those fields into operators for you:
response = session.post(f"{API}/v1/x/search", json={
"fromUsers": ["XDevelopers"],
"minLikes": 500,
"onlyOriginal": True, # exclude replies
"since": "2026-08-01T00:00:00Z",
"limit": 20,
}, timeout=60)
response.raise_for_status()
for post in response.json()["data"]:
print(post["createdAt"][:10], post["likeCount"], post["id"])
print("credits:", response.headers["x-credits-charged"])
We ran this on 19 October with limit: 2. It returned two posts and charged 3 credits. One item, trimmed:
{
"id": "2107953725071626260",
"text": "We teamed up with ... to put the pulse of X at your fingertips 🤝 ...",
"url": "https://x.com/XDevelopers/status/2107953725071626260",
"createdAt": "2026-10-07T21:58:26.000Z",
"author": { "username": "XDevelopers", "followersCount": 698067 },
"likeCount": 758,
"retweetCount": 45,
"viewCount": 31280
}
Fields use X's own names.
Keep id as a string, because X ids are too big for a float. A null count means X didn't report it, not zero.
Step 3: Get one account's tweets
An account's timeline is GET /v1/x/users/{user}/posts. {user} takes a username or a numeric id, and limit goes up to 20:
response = session.get(f"{API}/v1/x/users/XDevelopers/posts",
params={"limit": 20}, timeout=60)
response.raise_for_status()
timeline = response.json()["data"]
It returns posts and reposts, newest first, with any pinned post on top. Our run put @XDevelopers' pinned February post first:
{
"id": "2019881223666233717",
"text": "Officially launching X API Pay-Per-Use ...",
"createdAt": "2026-02-06T21:09:45.000Z",
"likeCount": 5595
}
Replies live at /v1/x/users/{user}/replies. A protected or missing account returns 404. To go further back than the timeline reaches, see how to download all tweets from a user.
Step 4: Page through results with the cursor
Every list response carries meta.nextCursor. Send it back unchanged to get the next page; null is the only stop.
Search takes the cursor in the body. GET endpoints take it in the query string.
def search_pages(body, max_pages=10):
cursor = None
for _ in range(max_pages):
payload = {**body, "cursor": cursor} if cursor else body
r = session.post(f"{API}/v1/x/search", json=payload, timeout=60)
if r.status_code == 429: # too fast: wait, then retry
time.sleep(int(r.headers.get("Retry-After", "5")))
continue
r.raise_for_status() # a 402 means out of credits: stop
page = r.json()
yield from page["data"]
cursor = page["meta"]["nextCursor"]
if not cursor:
return
Three things this loop gets right:
- A page ceiling.
max_pagesstops a broad query from paging, and billing, forever. 429and402differ. A429clears afterRetry-After; a402needs a top-up.- The body never changes. A cursor is bound to its request, and a changed filter gets a
400.
X serves about 20 posts per search page however high you set limit.
Step 5: Save tweets to CSV
DictWriter with extrasaction="ignore" keeps the columns you name and drops the rest:
import csv
FIELDS = ["id", "createdAt", "username", "text", "likeCount", "viewCount", "url"]
query = {"query": "python", "language": "en", "minLikes": 50, "onlyOriginal": True}
with open("posts.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=FIELDS, extrasaction="ignore")
writer.writeheader()
for post in search_pages(query, max_pages=5):
writer.writerow({**post, "username": post["author"]["username"]})
Keep encoding="utf-8", because posts are full of emoji.
Excel shows long ids in scientific notation. That's only the display; the CSV keeps every digit.
What does it cost to get 10,000 tweets?
A search call costs 1 credit plus 1 per post, so a 20-post page is 21 credits.
That's 500 pages, or 10,500 credits. The $5 pack holds 25,000 credits that never expire.
The 5,000 free monthly credits cover about 238 full pages, or 4,760 posts. Price your own job with the X API cost calculator.
When not to use Weir
- You need to post or act for users. Only X's own API can write.
- You need a contract with X itself, or your company requires first-party data.
- You need 500 posts per archive request. X's full-archive search returns more per call.
- Bulk volume is your only goal. Some third parties charge less per post; see Twitter API alternatives.
Once the posts are in a DataFrame, Twitter data analysis in Python continues with pandas.
For a live feed rather than a search, see the filtered stream in Python.
X's official SDK is covered in the XDK Python tutorial.
FAQ
Can I still get tweets with Python for free?
Partly. The official X API has no free tier for new apps. Scraping libraries cost nothing but need your own accounts and break often. Weir gives 5,000 free credits a month, which is about 4,760 posts.
Does Tweepy still work in 2026?
Yes. Tweepy is maintained and works with the X API v2, at version 4.17.0. You still pay X's rates, $0.005 per post read, and need a bearer token from a developer account with credits.
Why does snscrape no longer work for Twitter?
Its Twitter scrapes started failing with "blocked (404)" errors in June 2023. That issue, #996, is still open, and the last release dates from the same month. Treat its Twitter module as dead.
How many tweets can I get per request?
On Weir, about 20 per search page, whatever limit you set. X's recent search returns up to 100 per request, and its full-archive search up to 500.
Sources
- X API pay-per-usage pricing (checked 19 October 2026): https://docs.x.com/x-api/getting-started/pricing
- X API search introduction: https://docs.x.com/x-api/posts/search/introduction
- X API search operators: https://docs.x.com/x-api/posts/search/integrate/operators
- X Terms of Service (effective 9 October 2026): https://x.com/en/tos
- Tweepy on PyPI (4.17.0, July 2026): https://pypi.org/project/tweepy/
- XDK, X's Python SDK, on PyPI: https://pypi.org/project/xdk/
- snscrape on PyPI (last release June 2023): https://pypi.org/project/snscrape/
- snscrape issue #996 (opened 30 June 2023): https://github.com/JustAnotherArchivist/snscrape/issues/996
- twikit on PyPI (2.3.3, February 2025): https://pypi.org/project/twikit/
- twikit issue #425: https://github.com/d60/twikit/issues/425
- twscrape on PyPI (0.21.0, November 2026): https://pypi.org/project/twscrape/
- twscrape README: https://github.com/vladkens/twscrape
- Weir billing and tiers: https://docs.weirapp.io/billing
- Weir pagination: https://docs.weirapp.io/pagination