By Sorsa Editorial

Updated June 2026: refreshed X's pay-per-use pricing (including the April 2026 write-cost changes), reconfirmed the official XDK and Tweepy against the current API, and updated the cost math against Sorsa's current plans.

Key Takeaway: There are four practical ways to get Twitter/X data with Python in 2026: X's official SDK (pip install xdk), Tweepy, plain requests with a bearer token, or a third-party REST API. The official routes bill per resource and require OAuth; a read-only third-party API needs only an API key and suits read-heavy work.

If you searched "twitter api python" expecting a quick pip install and a working snippet, the current landscape is messier than the old tutorials suggest. The X (formerly Twitter) API changed its pricing model, changed its authentication, and now ships an official Python SDK that did not exist a year ago.

We build and run Sorsa API, an alternative Twitter/X API, so the read-only path is the one we know best: it returns profiles, tweets, search, and followers as clean JSON from plain requests, with one API key in the header, no OAuth flow, and no developer-account approval to wait on. On read-heavy work it runs up to roughly 50x cheaper than the official X API, holds a flat 20 requests per second on every plan, and starts at $49 a month for 10,000 requests. Not every project fits that mold: some need to post, some need the official API for compliance, and some developers just want to understand how everything works. This guide covers all four methods with working Python code, a side-by-side comparison, current pricing, and a complete data collector that paginates and loads results straight into pandas. You can also test calls without writing code in the Sorsa API playground.

Table of contents

  • What changed: X API in 2026
  • Best Python library for the X API v2 (quick answer)
  • Which approach should you use?
  • Method 1: Official X Python SDK (XDK)
  • Method 2: Tweepy
  • Method 3: Plain Python requests with a bearer token
  • Method 4: Third-party API with Python requests
  • Building a production data collector: pagination, retries, and pandas
  • Comparison: all four methods side by side
  • How to get your API credentials
  • Common tasks: code examples
  • In practice: moving read-only pulls off the official API
  • FAQ
  • Getting started

What Changed: X API in 2026

If the last time you touched the Twitter API was 2023 or earlier, here is what is different.

Pay-per-use is the default. In early 2026 X replaced its old subscription tiers with a consumption model. There is no $100 Basic or $5,000 Pro plan for new signups, and there is no free tier. You buy credits upfront and pay per resource you read: $0.005 per post, $0.010 per user profile, and $0.010 per follower or following record. Reading your own account's data (your timeline, your bookmarks, your followers) is cheaper at $0.001 per resource, but that discounted rate does not apply when you read other accounts.

Writing got more expensive after the April 2026 update. A standard post now costs $0.015 per request, and a post that contains a URL jumps to $0.20. Follow, like, and quote-post actions were pulled from the self-serve tiers entirely and now require an Enterprise contract. If you were planning a follow-back bot or an auto-liker, that is no longer possible on a standard pay-per-use account.

There is a hard read cap. Standard accounts are limited to 2 million post reads per month. X also returns a portion of your spend as xAI (Grok) API credits, up to 20 percent at higher volumes. For a full breakdown of what this means for a real budget, see our X API pricing analysis and our explainer on why the Twitter API is so expensive.

X released an official Python SDK. The XDK (X Developer Kit) is an auto-generated SDK with type hints, automatic pagination, and streaming support. Install it with pip install xdk. It is the first official Python library X has ever shipped.

Tweepy still works. It supports X API v2 and remains the most mature community library. Existing Tweepy code runs fine with current credentials.

Old libraries are dead. The original python-twitter package by bear is archived, and the twitter package on PyPI has not been updated in years. If a tutorial tells you to pip install python-twitter, that tutorial is outdated. (A separate, actively maintained v2 wrapper published by sns-sdks is covered in the next section.)


Best Python Library for the X API v2 (Quick Answer)

If you only want the short version: Tweepy is the best general-purpose Python library for the X API v2, because it is mature, well documented, and supports both read and write through bearer-token and OAuth flows. If you want a first-party tool that tracks the API spec exactly, use the official XDK. For read-only data collection, many developers skip libraries entirely and call a third-party REST API with plain requests (see Method 4).

Here is how the main options compare.

Library / toolTypeBest forNotes
TweepyCommunityGeneral integration, bots, scriptsMature, large community, handles pagination and rate-limit retries. Needs paid X API credentials.
XDK (X Developer Kit)OfficialSpec-strict projects, new buildsGenerated from OpenAPI specs, typed models, young (launched early 2026).
Twarc2CommunityAcademic research, archivingCommand-line first, waits out rate limits, stores JSON for offline analysis.
python-twitter (sns-sdks)CommunityLightweight v2 wrapperSimple, focused on v2 endpoints. Smaller community than Tweepy.
requests (no wrapper)StandardMinimal dependencies, custom clientsYou build pagination and error handling yourself. Pairs well with third-party APIs.

Every official-API library above bills through X's pay-per-use pricing. The cost is identical whether you call X with the XDK, Tweepy, or raw requests, because the charge is per resource on X's side, not per library. The variable you actually control is how many resources you pull, which is where a third-party API and batch endpoints change the math (covered below).


Which Approach Should You Use?

Pick the path before writing code. It saves hours.

If you need...Use...
Read and write with full official supportOfficial XDK or Tweepy
Read-only data at scale, minimal setupThird-party API (for example, Sorsa)
Full control over HTTP, no dependenciesPlain requests plus a bearer token
Write actions (post, and on Enterprise: like, follow)Official XDK or Tweepy (OAuth required)

If your project only reads public data (profiles, tweets, search results, followers), a third-party API removes the OAuth dance: one API key in a header and you start pulling data, with no developer-account application and no credit purchase. If you need to post or perform write actions, you must use the official X API through the XDK, Tweepy, or raw requests. No third-party provider posts on your behalf.


Method 1: Official X Python SDK (XDK)

The XDK is X's first official Python SDK. It wraps the entire v2 API surface with typed models, handles pagination automatically, and supports all three authentication methods (bearer token, OAuth 2.0 PKCE, OAuth 1.0a).

Install it:

bash
pip install xdk

Search for Recent Tweets

python
import os
from xdk import Client

client = Client(bearer_token=os.environ["BEARER_TOKEN"])

response = client.posts.recent_search(query="python lang:en")

for post in response.data:
    print(f"@{post.author_id}: {post.text[:120]}")

This returns posts matching your query from the last 7 days. The response object includes pagination tokens, so you can loop through pages without tracking cursors by hand.

Look Up a User Profile

python
user = client.users.find_by_username(username="elonmusk")
print(f"@{user.data.username} - {user.data.public_metrics}")

Post a Tweet (Requires OAuth 2.0)

Write operations need user-context authentication. Set your Client ID and Client Secret as environment variables, then:

python
client = Client(
    client_id=os.environ["CLIENT_ID"],
    client_secret=os.environ["CLIENT_SECRET"],
)

client.posts.create(post_data={"text": "Hello from the XDK!"})

The XDK handles the OAuth 2.0 PKCE flow internally, including token refresh.

When to Use the XDK

The XDK is the right pick if you want official support, need write access, and are starting a new project. The typed models make IDE autocomplete work well, and automatic pagination saves boilerplate. The downsides: the SDK is young (launched in early 2026, with a small but growing GitHub following), documentation is still thin, and you pay X's pay-per-use pricing for every request, so a post read costs $0.005 and a user lookup costs $0.010 and those charges stack up at scale. Full SDK docs live at docs.x.com/xdks/python/overview.


Method 2: Tweepy

Tweepy has been around since 2009 and remains the most popular Python library for the Twitter API. It supports X API v2, handles rate limiting, and has extensive community documentation.

Install it:

bash
pip install tweepy

Search for Recent Tweets

python
import os
import tweepy

client = tweepy.Client(bearer_token=os.environ["BEARER_TOKEN"])

response = client.search_recent_tweets(
    query="python lang:en",
    max_results=10,
    tweet_fields=["created_at", "public_metrics"],
)

for tweet in response.data:
    metrics = tweet.public_metrics
    print(tweet.text[:120])
    print(f"  Likes: {metrics['like_count']}  Retweets: {metrics['retweet_count']}")

Get a User's Followers

python
user = client.get_user(username="elonmusk")
followers = client.get_users_followers(
    id=user.data.id,
    max_results=100,
    user_fields=["description", "public_metrics"],
)

for follower in followers.data:
    print(f"@{follower.username} - {follower.public_metrics['followers_count']} followers")

Post a Tweet

python
client = tweepy.Client(
    consumer_key=os.environ["API_KEY"],
    consumer_secret=os.environ["API_SECRET"],
    access_token=os.environ["ACCESS_TOKEN"],
    access_token_secret=os.environ["ACCESS_TOKEN_SECRET"],
)

client.create_tweet(text="Hello from Tweepy!")

When to Use Tweepy

Tweepy is the safe default for most Python developers. It is battle-tested, the community is large, and there is a Stack Overflow answer for almost any issue. It wraps rate-limit handling, retries, and pagination in a clean interface. The tradeoffs match the XDK: you still need an X developer account, you still pay per resource, and rate limits are inherited from the official API (typically 300 requests per 15-minute window for search, though this varies by endpoint). If you already have Tweepy code running, there is no reason to migrate to the XDK unless you need a feature Tweepy lacks. Full docs: docs.tweepy.org.


Method 3: Plain Python requests with a Bearer Token

No libraries, no wrappers, just HTTP requests. This approach suits developers who want full control over what gets sent and received, or who work in environments where installing third-party packages is restricted.

Search for Recent Tweets

python
import os
import requests

search_url = "https://api.x.com/2/tweets/search/recent"
headers = {"Authorization": f"Bearer {os.environ['BEARER_TOKEN']}"}
params = {
    "query": "python lang:en",
    "max_results": 10,
    "tweet.fields": "created_at,public_metrics,author_id",
}

response = requests.get(search_url, headers=headers, params=params)
data = response.json()

for tweet in data["data"]:
    print(tweet["text"][:120])
    print(f"  Likes: {tweet['public_metrics']['like_count']}")

Get a User Profile

python
user_url = "https://api.x.com/2/users/by/username/elonmusk"
headers = {"Authorization": f"Bearer {os.environ['BEARER_TOKEN']}"}
params = {"user.fields": "description,public_metrics,created_at"}

response = requests.get(user_url, headers=headers, params=params)
user = response.json()["data"]

print(f"@{user['username']} - {user['public_metrics']['followers_count']} followers")

Handling Pagination Manually

python
search_url = "https://api.x.com/2/tweets/search/recent"
next_token = None
all_tweets = []

while True:
    params = {
        "query": "python lang:en",
        "max_results": 100,
        "tweet.fields": "created_at,public_metrics",
    }
    if next_token:
        params["next_token"] = next_token

    response = requests.get(search_url, headers=headers, params=params)
    data = response.json()
    all_tweets.extend(data.get("data", []))

    next_token = data.get("meta", {}).get("next_token")
    if not next_token:
        break

print(f"Collected {len(all_tweets)} tweets")

When to Use Raw Requests

This works when you want zero dependencies beyond requests, when you are debugging API behavior, or when you call just one or two endpoints and a full SDK is overkill. The downside is obvious: you handle pagination, error codes, rate limiting, and retry logic yourself. For a one-off script that is fine. For a production pipeline you will end up writing your own wrapper, at which point you have reinvented Tweepy. This method still requires an X developer account and pay-per-use credits, and the header uses a bearer token for read-only access.


Method 4: Third-Party API with Python requests

If your project only needs to read public Twitter data, skip the official API entirely and call a third-party data provider. This is the practical route to Twitter data without a developer account: no OAuth, no application step, no credit-purchase workflow, just one API key in a header, standard REST calls, and JSON responses. Here is what that looks like with Sorsa's API.

Get a User Profile

python
import requests

headers = {"ApiKey": "YOUR_SORSA_API_KEY"}

response = requests.get(
    "https://api.sorsa.io/v3/info",
    headers=headers,
    params={"username": "elonmusk"},
)

user = response.json()
print(f"@{user['username']}: {user['display_name']}")
print(f"Followers: {user['followers_count']}")
print(f"Tweets: {user['tweets_count']}")

The response includes the full profile in one request: ID, username, display name, bio, location, follower and following counts, tweet and media counts, verification status, profile images, account creation date, pinned tweets, and bio URLs.

Search Tweets

python
response = requests.post(
    "https://api.sorsa.io/v3/search-tweets",
    headers=headers,
    json={"query": "python programming", "order": "popular"},
)

for tweet in response.json()["tweets"]:
    print(f"@{tweet['user']['username']}: {tweet['full_text'][:120]}")
    print(f"  Likes: {tweet['likes_count']}  Views: {tweet['view_count']}")

Each search request returns up to 20 tweets, and every tweet includes the full author profile in the user field. There is no extra request (and no extra charge) to get the tweeter's follower count or verification status, unlike the official API where expanding user data adds $0.010 per user. The search endpoint supports the same advanced operators you would type into X search (from:, to:, since:, until:, quoted phrases, hashtags). The full list is in our Twitter search operators cheat sheet.

Get Followers

python
response = requests.get(
    "https://api.sorsa.io/v3/followers",
    headers=headers,
    params={"username": "elonmusk"},
)

for follower in response.json()["users"][:5]:
    print(f"@{follower['username']} - {follower['followers_count']} followers")

The followers endpoint returns up to 200 full profiles per request, with pagination through a next_cursor parameter.

Fetch Multiple Tweets in Bulk

python
response = requests.post(
    "https://api.sorsa.io/v3/tweet-info-bulk",
    headers=headers,
    json={
        "tweet_links": [
            "https://x.com/elonmusk/status/1234567890",
            "https://x.com/OpenAI/status/9876543210",
            "1122334455667788",
        ]
    },
)

for tweet in response.json()["tweets"]:
    print(f"@{tweet['user']['username']}: {tweet['full_text'][:100]}")

The /tweet-info-bulk endpoint accepts up to 100 tweet URLs or IDs in a single request and returns complete tweet objects with author data. One call, 100 tweets.

Why This Approach Works for Read-Only Projects

Methods 1 to 3 require an X developer account (with an application step), purchased credits, OAuth tokens, and per-resource billing. Method 4 needs one API key in a header. Sorsa uses flat per-request pricing: one call is one request from your quota regardless of how many tweets or profiles it returns, so a search returning 20 tweets costs the same as a single ID lookup. On the Pro plan ($199 per month for 100,000 requests) that works out to $0.00199 per request, and the rate limit is 20 requests per second on every plan, with no 15-minute windows.

The tradeoff is that there is no write access: you cannot post, like, or follow through a read-only third-party API. If you need those, use Methods 1 or 2 for the writes and a third-party API for the read-heavy work. That hybrid is exactly what we set up for a fintech client running a sentiment pipeline: they had been paying $5,000 per month on a legacy Pro plan, we moved all reads (mention tracking, competitor monitoring, follower analysis) to a third-party provider and kept a minimal official setup for posting alerts, and their total spend dropped below $250 per month. If you are coming from the official API, our migration guide maps endpoints and field names.


Building a Production Data Collector: Pagination, Retries, and pandas

The single-call examples above are enough to test your key, but real data work needs three more things: pagination to get past the first 20 results, error handling so one bad response does not kill a long run, and a way to turn the JSON into something you can analyze. Here is a complete, runnable collector that does all three against Sorsa, then loads the results into a pandas DataFrame and saves them to CSV.

python
import os
import time
import requests
import pandas as pd

API_KEY = os.environ["SORSA_API_KEY"]   # read the key from the environment, never hard-code it
BASE = "https://api.sorsa.io/v3"
HEADERS = {"ApiKey": API_KEY}


def post_with_retry(path, payload, retries=3):
    """POST to Sorsa with exponential backoff on transient errors and 429 responses."""
    for attempt in range(retries):
        try:
            response = requests.post(f"{BASE}{path}", headers=HEADERS, json=payload, timeout=30)
            response.raise_for_status()
            return response.json()
        except requests.HTTPError as error:
            status = error.response.status_code
            if status == 429 and attempt < retries - 1:   # rate limited: wait and retry
                time.sleep(2 ** attempt)
                continue
            raise   # 401 (bad key), 400 (bad params), and the final 429 surface here
        except requests.RequestException:
            if attempt == retries - 1:
                raise
            time.sleep(2 ** attempt)


def collect_tweets(query, order="latest", max_pages=5):
    """Collect tweets for a query, following next_cursor pagination up to max_pages."""
    cursor, rows = None, []
    for page in range(max_pages):
        payload = {"query": query, "order": order}
        if cursor:
            payload["next_cursor"] = cursor
        data = post_with_retry("/search-tweets", payload)
        batch = data.get("tweets", [])
        rows.extend(batch)
        print(f"page {page + 1}: +{len(batch)} tweets (total {len(rows)})")
        cursor = data.get("next_cursor")
        if not cursor:        # no cursor means there are no more pages
            break
    return rows


if __name__ == "__main__":
    tweets = collect_tweets('"machine learning" lang:en', max_pages=3)
    df = pd.json_normalize(tweets)
    df.to_csv("tweets.csv", index=False)
    print(f"Saved {len(df)} rows to tweets.csv")

A few things worth calling out:

  • Pagination uses next_cursor. Each /search-tweets response returns up to 20 tweets plus a next_cursor. Pass that cursor back in the body of the next request and repeat until it is empty. The max_pages guard stops a broad query from running away and burning through your quota. Our pagination reference documents the cursor flow in detail.
  • Retries and backoff. raise_for_status() turns failed responses into exceptions. A 429 (you exceeded the 20 requests-per-second limit) triggers a short exponential backoff and a retry. A 401 means a bad key and surfaces immediately, so you notice it instead of silently collecting nothing.
  • The key lives in an environment variable. Set it once with export SORSA_API_KEY='your_key' and read it with os.environ. Never commit the key to source control.

Loading the Data into pandas

pandas.json_normalize flattens the nested tweet objects (including the embedded author under user.*) into a flat table in one line:

python
df = pd.json_normalize(tweets)

# Keep the columns most analyses need
columns = [
    "id", "full_text", "created_at", "lang",
    "likes_count", "retweet_count", "reply_count", "view_count",
    "user.username", "user.followers_count", "user.verified",
]
df = df[columns]

# Example: engagement rate per tweet
df["engagement_rate"] = (
    df["likes_count"] + df["retweet_count"] + df["reply_count"]
) / df["view_count"].clip(lower=1)

df.to_csv("tweets.csv", index=False)      # portable, opens in Excel or Sheets
df.to_parquet("tweets.parquet")           # compact, fast to reload for repeated analysis

From here you can group by author, compute engagement rates, run sentiment classification (see our Twitter sentiment analysis guide), or build a training dataset for a model. Because every tweet already includes the full author profile, you do not need a second call per author to get follower counts or verification status, which is the main reason this pattern stays cheap at scale.


Comparison: All Four Methods Side by Side

Official XDKTweepyPlain requestsSorsa API
Installpip install xdkpip install tweepyBuilt-inBuilt-in (requests)
AuthBearer or OAuth 2.0 PKCEBearer or OAuth 1.0aBearer token headerApiKey header
Read accessYes (paid per resource)Yes (paid per resource)Yes (paid per resource)Yes (paid per request)
Write accessYesYesYesNo
Rate limitsPer-endpoint window (~300/15 min)Inherited from X APIInherited from X API20 req/s (all endpoints)
PaginationAutomaticAutomaticManualManual (next_cursor)
Setup time~30 min~15 min~10 min~5 min (no approval)
Best forNew projects needing full APIMature projects, communityLearning, minimal depsRead-only data at scale

How to Get Your API Credentials

X Developer Account (Methods 1 to 3)

  1. Go to developer.x.com, sign in with your X account, and create a Project and an App inside it.
  2. For read-only access, copy your Bearer Token. This single token is enough for search, user lookups, and timelines.
  3. For posting and other write actions, open User Authentication Settings and set permissions to Read and Write, then generate the four OAuth 1.0a credentials: API Key (Consumer Key), API Key Secret (Consumer Secret), Access Token, and Access Token Secret. All four are required to post.
  4. Purchase credits in the Developer Console. Pay-per-use has no minimum spend, but your balance must be above zero before any authenticated call will succeed.

Store credentials in environment variables, never in code:

bash
export BEARER_TOKEN='AAAAAAAAAAAAAAAAAAAAAxxxxxxx'
export API_KEY='your_api_key'
export API_SECRET='your_api_secret'
export ACCESS_TOKEN='your_access_token'
export ACCESS_TOKEN_SECRET='your_access_token_secret'

For a screenshot-by-screenshot walkthrough of the portal, including where to find the bearer token and how to switch permissions to Read and Write, see our guide on how to get a Twitter/X API key. For what each credential costs per request, see the X API pricing breakdown.

Sorsa API Key (Method 4)

  1. Go to api.sorsa.io/overview and create an account.
  2. Your API key is generated immediately on the keys page.
  3. Start making requests. No application process, no credit-purchase step.

The quickstart guide walks through your first call in under a minute, and the authentication docs cover the ApiKey header in detail.


Common Tasks: Code Examples

How to Search Tweets by Keyword

All four methods support keyword search. Methods 1 to 3 use the X API v2 recent-search endpoint (last 7 days, or the full archive on legacy Pro). Method 4 searches the full public archive. To build complex queries, combine operators: "machine learning" from:OpenAI since:2026-01-01 -is:retweet returns original posts from @OpenAI mentioning the phrase since January 2026. For a visual builder, use the Sorsa search builder; the complete operator reference is in our search operators cheat sheet.

How to Get Historical Tweets

The recent-search endpoint on the official API only covers the last 7 days unless you have legacy full-archive access. A third-party API searches the full archive directly, and date operators (since:, until:) let you page back through older posts. For large historical pulls and the tradeoffs involved, see our guide to historical Twitter data.

How to Get a User's Followers

On the official API, follower lists are paginated at 100 users per page and each profile is a billable $0.010 resource, so 1,000 followers costs about $10 in user reads. Through Sorsa, /followers returns up to 200 profiles per request, so 1,000 followers is 5 requests, roughly $0.01 on the Pro plan. More detail is in our followers API guide.

How to Fetch Tweet Data by ID

When you have a list of tweet IDs, batch lookups are the efficient path. On the official API, GET /2/tweets?ids=... accepts up to 100 IDs and bills $0.005 per returned tweet. With Sorsa, POST /tweet-info-bulk accepts up to 100 URLs or IDs and counts as one request, returning complete tweet objects with author data.


In Practice: Moving Read-Only Pulls off the Official API

A pattern we see often: a team starts on the official X API with Tweepy because that is what the old tutorials show, then hits friction on a project that only reads data. One analytics team came to us after building a daily collector that pulled profiles and recent tweets for a few thousand tracked accounts. The code worked, but every run burned billable post and user reads, the developer-account approval and OAuth refresh logic added setup time, and the 2-million-reads monthly cap meant they had to watch volume closely as their account list grew.

The fix was not a rewrite, just a swap at the transport layer. The collection logic, the pandas normalization, and the scheduling all stayed the same. They replaced the Tweepy client with the plain requests pattern from Method 4, pointed it at the search and /followers endpoints, and dropped the OAuth flow entirely (one ApiKey header instead of token management). Because each request returns up to 20 tweets or 200 follower profiles rather than billing per resource, the same daily pull cost a fraction of what it had, and a per-second limit replaced the monthly cap as the only thing to pace against. For a read-only workload, the official API had been the expensive way to do a simple job.


FAQ

Is there a free Twitter API for Python in 2026?

No. The official X API no longer has a free tier. The pay-per-use model requires purchasing credits before making any request, and there are no free credits for new accounts. Some third-party providers offer free trials or limited free tiers, so check individual providers for current offers. For a full breakdown of which X API tiers remain free, see our analysis of whether the Twitter API is free in 2026.

What is the easiest way to get Twitter data in Python?

Call a third-party REST API with the requests library: get an API key, pass it in a header, and POST your query to a search endpoint. The JSON maps straight to Python dicts and into pandas. It is simpler than the official API plus Tweepy because there is no OAuth flow and no developer-account approval to wait on.

How do you load tweets into a pandas DataFrame in Python?

Collect the tweet objects into a list, then call pandas.json_normalize(tweets) to flatten the nested fields (including the embedded author) into a DataFrame in one line. Save with df.to_csv("tweets.csv", index=False) for a portable file, or df.to_parquet(...) for a compact columnar file you can reload quickly. From there you can filter, group, and compute engagement metrics with normal pandas.

How do you paginate through tweets in Python?

Each response includes a next_cursor (or next_token on the official API). Pass it back on the next request and repeat until it is empty. Always cap the loop with a max_pages guard so a broad query does not run away and consume your quota. The collector script above shows the pattern.

Can you get Twitter data with Python without an API key?

Technically yes, through web scraping with libraries like Twikit or Playwright, but scrapers break every 2 to 4 weeks when X rotates internal tokens and GraphQL identifiers, and you risk account bans. For reliable access, an API key (from X or a third-party provider) is the practical path. See our guide to scraping X for the technical approach or our Twitter scrapers comparison for managed options.

How much does Twitter API access cost for Python developers?

On the official X API: $0.005 per post read, $0.010 per user profile read, $0.015 per standard post created, and $0.20 for a post that contains a URL. A search returning 20 tweets costs $0.10, and fetching 1,000 follower profiles costs about $10. There is a 2 million post reads per month cap. On Sorsa: plans start at $49 per month for 10,000 requests, and each request returns up to 20 tweets or 200 follower profiles, so the effective per-item cost is far lower. For a detailed comparison, see our pricing breakdown.

Does Tweepy still work in 2026?

Yes. Tweepy supports X API v2 and works with current authentication (bearer tokens and OAuth). It requires paid X API credentials: there is no way to use Tweepy without an active X developer account with purchased credits under pay-per-use.

How do you handle rate limits with the Twitter API in Python?

The official API enforces limits per 15-minute window (typically 300 to 900 requests depending on the endpoint) and returns a 429 with a Retry-After header when you hit one. Tweepy and the XDK back off automatically; with raw requests you check the headers and sleep before retrying. For a full table of limits per endpoint, see our X API rate limits guide. A third-party API like Sorsa uses a per-second limit (20 requests per second) instead of windows, so on a 429 you wait one second and retry.


Getting Started

Pick a method and run one of the examples above.

  • Read-only data: grab a key from the Sorsa dashboard, paste it into the headers dict in any Method 4 example, and run the script. You will have structured Twitter data in your terminal in under a minute. The documentation covers all 40 endpoints.
  • Read and write: create an X developer account at developer.x.com, purchase credits, and run the XDK or Tweepy examples with your bearer token.
  • No code yet: the browser-based playground lets you test any endpoint through a web UI before writing a line of Python.

For a broader look at read-only providers, see our Twitter API alternatives comparison.


Reviewed by Keksich, founder of Sorsa, marketer and X API researcher.

How We Verified This Guide

We checked every external claim against primary sources in June 2026. The official XDK details (the pip install xdk package, auto-generated client, automatic pagination, streaming, and the three authentication methods) come from X's developer announcement of the Python and TypeScript XDKs and the XDK documentation on docs.x.com. Tweepy's continued v2 support was confirmed against the Tweepy documentation. The X API pricing figures reflect the current pay-per-use model, including the April 2026 write-cost changes, and the Sorsa endpoint behavior, per-request batching, and plan pricing come from the Sorsa API documentation. We do not cite tweet counts or library star counts, since those numbers move; where a figure could date, we describe the mechanism instead. If you spot a number that has shifted since publication, the in-product docs are always the current source of truth.