Install requests and set the key
Keep the key in an environment variable. Do not paste it into a Python file, notebook output, screenshot, or Git repository.
python -m pip install requests
export TWITTERXAPI_KEY="tx_live_..."Fetch a public X profile
Use the moderate response level for stable names. raise_for_status() stops error JSON from entering the rest of the program.
import os, requests
r = requests.get(
"https://twitterxapi.com/api/v1/users/marclou",
headers={"Authorization": f"Bearer {os.environ['TWITTERXAPI_KEY']}"},
params={"level": "moderate"}, timeout=30
)
r.raise_for_status()
profile = r.json()
print(profile["username"], profile["followersCount"]){
"id": "2311987360",
"username": "marclou",
"followersCount": 382499,
"followingCount": 1246,
"statusesCount": 36756,
"verified": false
}Build a reusable cursor iterator
Keep authentication, status checks, and cursor handling in one generator.
def items(session, url):
cursor = None
while True:
params = {"level": "moderate"}
if cursor: params["cursor"] = cursor
r = session.get(url, params=params, timeout=60)
r.raise_for_status()
page = r.json()
yield from page["items"]
cursor = page["pagination"]["next_cursor"]
if not page["pagination"]["has_more"] or not cursor:
returnHandle errors
Treat 401 as a key problem, 402 as insufficient credit, 429 as a temporary rate limit, and 5xx responses as retryable service errors. Log the response request ID when available.
Only successful responses that return data are billed. Failed requests are free.
COMMON QUESTIONS
Frequently asked questions
Do I need a Python Twitter library?+
No. The requests package is enough because TwitterXAPI is JSON over HTTPS.
How do I hide the API key?+
Store it in an environment variable or secret manager.
How do I get all pages?+
Send pagination.next_cursor on the next request until has_more is false.
TRY THE API
Make the first request today.
One key covers REST and MCP. Add credit when you need it.
Get an API key