SorsaSorsaGet API Key
Return to blog

Twitter API Python: Complete Guide to Getting X Data in 2026

4 ways to access Twitter/X data with Python: official XDK, Tweepy, plain requests, and third-party APIs. Working code examples for each.

How to Use the Twitter API with Python in 2026 (4 Methods Compared)

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 right choice depends on whether you need write access (posting, liking), how much you want to spend, and how much OAuth setup you are willing to deal with. Read-only projects have simpler, cheaper options than projects that need to post.

Last updated: March 24, 2026


If you searched "twitter api python" expecting to find a quick pip install and a working code snippet, you are in for a surprise. The X (formerly Twitter) API has changed dramatically since most existing tutorials were written. The pricing model is different, the authentication is different, and there is now an official Python SDK that did not exist a year ago.

At Sorsa API, we handle millions of Twitter data requests for developers who need read-only access without the OAuth overhead. But not every project fits that mold. Some need write access. Some need the official API for compliance reasons. Some developers just want to learn how everything works under the hood.

This guide covers all four methods with working Python code, a side-by-side comparison, and a decision framework so you can skip the ones that do not apply to your project. You can also test API calls without writing code using the Sorsa API playground.

Table of Contents


What Changed: X API in 2026

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

Pay-per-use is now the default. In February 2026, X replaced its subscription tiers with a consumption-based model. No more $200/month Basic or $5,000/month Pro plans for new signups. You buy credits upfront and pay per resource: $0.005 per post read, $0.01 per user profile, $0.01 per post created. There is a hard cap of 2 million post reads per month on standard accounts. For a full breakdown of what this means for your budget, see our X API pricing analysis.

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 new (launched alongside the samples repo on GitHub), but 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. If you have existing Tweepy code, it will run fine with current credentials.

Old libraries are dead. The python-twitter package by bear is archived. 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.


Which Approach Should You Use?

Before diving into code, pick the right path. This saves hours.

If you need...Use...
Read + write with full official supportOfficial XDK or Tweepy
Read-only data at scale, minimal setupThird-party API (e.g., Sorsa API)
Full control over HTTP, no dependenciesPlain requests + bearer token
Write actions (post, like, follow)Official XDK or Tweepy (OAuth 2.0 required)

If your project only reads public data (profiles, tweets, search results, followers), a third-party API removes the OAuth dance entirely. You get a single API key, pass it as a header, and start pulling data. No developer account application, no credit purchases, no OAuth flows.

If you need to post tweets, like content, manage lists, or perform any write operation, you must use the official X API (through XDK, Tweepy, or raw requests). No third-party provider supports write operations 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:

pip install xdk

Search for Recent Tweets

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 up to 10 posts matching your query from the last 7 days. The response object includes pagination tokens, so you can loop through pages without manually tracking cursors.

Look Up a User Profile

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:

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 auto-generated type hints make IDE autocomplete work well, and automatic pagination saves boilerplate.

The downsides: the SDK is young (launched in early 2026, 22 stars on GitHub as of writing), documentation is still thin, and you are subject to X's pay-per-use pricing for every request. Every post read costs $0.005, every user lookup costs $0.01, and those charges stack up at scale.

Full SDK docs: 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:

pip install tweepy

Search for Recent Tweets

import tweepy
import os

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(f"{tweet.text[:120]}")
    print(f"  Likes: {metrics['like_count']}  Retweets: {metrics['retweet_count']}")

Get a User's Followers

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

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. The library is battle-tested, the community is large, and you will find a Stack Overflow answer for almost any issue. It wraps rate limit handling, retries, and pagination in a clean interface.

The tradeoffs are the same as the XDK: you still need an X Developer account, you still pay per resource under the new pricing model, 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 does not support.

Full docs: docs.tweepy.org


Method 3: Plain Python requests with Bearer Token

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

Search for Recent Tweets

import requests
import os

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(url, headers=headers, params=params)
data = response.json()

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

Get a User Profile

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(url, headers=headers, params=params)
user = response.json()["data"]

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

Handling Pagination Manually

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(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 approach works when you want zero dependencies beyond requests (or even the stdlib urllib), when you are debugging API behavior, or when you are calling 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. The authentication 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, there is a faster path: skip the official API entirely and use a third-party data provider. No OAuth, no developer account application, no credit purchase workflow. One API key in a header, standard REST calls, JSON responses.

Here is what this looks like with Sorsa API.

Get a User Profile

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']}")
print(f"Bio: {user['description'][:100]}")

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

Search Tweets

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

data = response.json()
for tweet in data["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 embedded in the user field. No extra request needed to get the tweeter's follower count, bio, or verification status. That is a significant cost difference from the official API, where expanding user data adds $0.01 per user to your bill.

The search endpoint supports Twitter's Advanced Search syntax: from:, to:, since:, until:, exact phrases in quotes, and hashtags. The full list of supported operators is in the search operators guide.

Get Followers

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

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

The followers endpoint returns up to 200 full user profiles per request, including bio, follower counts, verification status, and account creation date. Pagination works through a next_cursor parameter.

Fetch Multiple Tweets in Bulk

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. One API call, 100 complete tweets with author data. That kind of batching matters when you are processing data at scale.

Why This Approach Works for Read-Only Projects

The authentication story is the biggest difference. Methods 1-3 require an X Developer account (which involves an application process), purchasing credits, managing OAuth tokens, and dealing with per-resource billing. Method 4 needs one API key in a header.

Sorsa API uses flat per-request pricing. One API call equals one request from your quota, regardless of how many tweets or profiles it returns. A search that returns 20 tweets costs the same as a single ID conversion. On the Pro plan ($199/month for 100,000 requests), that works out to $0.00199 per request. The rate limit is 20 requests per second on all plans, with no 15-minute windows or per-endpoint restrictions. Custom higher limits are available on request.

The tradeoff is clear: no write access. You cannot post tweets, like content, or follow accounts through a third-party read-only API. If you need those capabilities, use Methods 1-3 for the write operations and a third-party API for the read-heavy work. That hybrid approach is exactly what I recommended to a fintech client running a sentiment analysis pipeline last year. They had been paying $5,000/month on the old Pro plan. We moved all their read operations (mention tracking, competitor monitoring, follower analysis) to a third-party provider and kept a minimal official API setup for posting alerts. Their total spend dropped below $250/month.


Comparison: All Four Methods Side by Side

Official XDKTweepyPlain requestsSorsa API
Installpip install xdkpip install tweepyBuilt-inBuilt-in (requests)
AuthBearer / OAuth 2.0 PKCEBearer / 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 limitsVaries by endpoint (~300/15 min)Inherited from X APIInherited from X API20 req/s (all endpoints)
PaginationAutomaticAutomaticManualManual (cursor-based)
Setup time~30 min~15 min~10 min~5 min
Best forNew projects needing full APIMature projects, community supportLearning, minimal depsRead-only data at scale

How to Get Your API Credentials

X Developer Account (Methods 1-3)

  1. Go to developer.x.com and sign in with your X account.
  2. Create a new Project and give it a name and description.
  3. Create an App within the project.
  4. Copy your Bearer Token for read-only operations. For write access, generate API Key, API Secret, Access Token, and Access Token Secret.
  5. Purchase credits in the Developer Console. Pay-per-use has no minimum spend, but your balance must be above zero before any API call will succeed.

Store credentials in environment variables. Never hardcode them:

export BEARER_TOKEN='AAAAAAAAAAAAAAAAAAAAAxxxxxxx'
export API_KEY='your_api_key'
export API_SECRET='your_api_secret'

For details on what each credential costs per request, see our 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 API call in under a minute. For authentication details, see the auth documentation.


Common Tasks: Code Examples

How to Search Tweets by Keyword

All four methods support keyword search. Methods 1-3 use the X API v2 recent search endpoint (last 7 days, or full archive on legacy Pro plans). Method 4 searches across the full public archive.

To build complex queries, combine operators: "machine learning" from:OpenAI since:2026-01-01 -is:retweet. This returns original tweets from @OpenAI mentioning "machine learning" since January 2026.

For a visual query builder, try the Sorsa search builder tool, which generates query strings you can paste into any of the methods above.

How to Get a User's Followers

On the official API, follower lists are paginated with a default of 100 users per page. Each user profile returned is a billable resource ($0.01). Fetching 1,000 followers costs $10 in user reads alone.

Through Sorsa API, the /followers endpoint returns up to 200 full profiles per request. Fetching 1,000 followers takes 5 requests. On the Pro plan, that is about $0.01 total. The followers documentation covers pagination details.

How to Fetch Tweet Data by ID

When you have a list of tweet IDs or URLs (from a spreadsheet, a database, or another API), batch lookups are the most efficient path.

On the official API, use GET /2/tweets?ids=id1,id2,... with up to 100 IDs. Each returned tweet is a $0.005 charge.

With Sorsa API, POST /tweet-info-bulk accepts up to 100 tweet URLs or IDs and returns complete tweet objects with author data. One request, regardless of how many tweets you send. The batch endpoint docs have the full request/response format.


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. There are no free credits for new accounts. Third-party providers sometimes offer free trials or limited free tiers - check individual providers for current offers.

What is the best Python library for the Twitter API?

It depends on your use case. The official XDK (pip install xdk) is the right choice for new projects that need both read and write access with type safety. Tweepy is better if you value community support, documentation, and battle-tested stability. For read-only data collection, plain requests against a third-party API like Sorsa is the simplest option, with no library to learn.

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

Technically, yes, through web scraping using libraries like Twikit or Playwright. But scrapers break every 2-4 weeks when X.com rotates internal tokens and GraphQL identifiers, and you risk account bans. For reliable data access, an API key (either 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.01 per user profile read, $0.01 per post created. A search returning 20 tweets costs $0.10. Fetching 1,000 follower profiles costs $10. There is a 2M post reads/month cap.

On Sorsa API: plans start at $49/month for 10,000 requests. Each request returns up to 20 tweets or 200 follower profiles, so the effective per-item cost is significantly lower.

For a detailed cost comparison, see our pricing breakdown.

Does Tweepy still work in 2026?

Yes. Tweepy supports X API v2 and works with current authentication methods (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 the new pay-per-use model.

What is the difference between Twitter API v1.1 and v2?

API v1.1 is largely deprecated. Most v1.1 endpoints either no longer work or require Enterprise access. API v2 is the current standard, with different endpoint URLs, a different response format (using data and includes objects), and new features like conversation threading and poll data. The XDK targets v2 exclusively. Tweepy supports both v1.1 and v2, but new projects should use v2.

How do I handle rate limits when using the Twitter API with Python?

The official API enforces rate limits per 15-minute window (typically 300-900 requests depending on the endpoint). For a complete table of limits per endpoint, see our X API rate limits guide. When you hit a limit, the API returns a 429 status code with a Retry-After header. Tweepy and the XDK handle this automatically. With raw requests, check the response headers and sleep before retrying.

Third-party APIs like Sorsa use a per-second rate limit (20 req/s) instead of windowed limits. If you exceed it, wait one second and retry. No 15-minute cooldowns.


Getting Started

If you made it this far, pick a method and run one of the code examples above. The fastest way to see results:

For read-only data: Grab an API key from the Sorsa API 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 38 endpoints. If you are migrating from the official X API, the migration guide maps endpoints and field names. For a comparison of third-party providers, see our X API alternatives guide.

For read + write: Create an X Developer account at developer.x.com, purchase credits, and run the XDK or Tweepy examples above with your bearer token.

For exploration: The Sorsa API playground lets you test any endpoint through a web UI with no code at all. Try a profile lookup or tweet search to see what the data looks like before writing a single line of Python.


Daniel Kolbassen is a data engineer and API infrastructure consultant with 12+ years of experience building data pipelines around social media platforms. He has worked with the Twitter/X API since the v1.1 era and has helped over 40 companies restructure their data infrastructure after the 2023 pricing overhaul. Follow him on Twitter/X or connect on LinkedIn.

Sorsa API — fast X (Twitter) data for developers

  • Real-time X data
  • 20 req/sec limits
  • AI-ready JSON
  • 30+ endpoints
  • Flat pricing
  • 3-minute setup
Share

More articles

All blog posts