Twitter (X) API 401 Unauthorized: What It Means and How to Fix It

- 401 = credential rejected. X defines it as "Invalid or missing authentication credentials"; a 403 means the credential was read but the endpoint or action is not allowed.
- X gives one body for every 401. 6 of our 8 broken X requests returned exactly
title: Unauthorized, detail: Unauthorized: no hint which cause you hit. - Wrong auth type is a 403, not a 401. A bearer token on
/2/users/meorPOST /2/tweetsreturned 403Unsupported Authenticationin 2 of 2 tries. - tweepy: catch
tweepy.errors.Unauthorized(401) separately fromtweepy.errors.Forbidden(403);get_meandcreate_tweetdefault touser_auth=True, so they need all four OAuth 1.0a values. - In public posts, 5 of 33 developers who named a cause blamed a bad, expired or mismatched key or token; 13 more suspected an X-side change, 12 of them in 2023.
- TwitterAPI.io: missing
x-api-key= 403, wrong or reset key = 401API key is invalid. Reads cost $0.15 per 1,000 tweets returned, no X account needed.
You copied the keys from the developer console, ran the sample, and got 401 Unauthorized. The error is short on detail by design, and the same three letters can mean a stale token, a stray space, a clock that drifted, or a request that never carried a credential at all. This page takes the error apart: what X's API v2 actually returns, which causes produce it, how tweepy surfaces it, and how to fix each one in the order that saves the most time.
The page's angle is evidence. We sent 15 requests with missing or obviously fake credentials (never a real key) to api.x.com/2 and to api.twitterapi.io, and publish every status code and body below. We also read 187 public posts about Twitter and X API 401 errors and hand-classified the causes developers reported. If your request gets past authentication and is then refused, that is a different error with different fixes: the sibling pages on the X API 403 Forbidden error and on error 400 cover those, and the error-handling guide covers retries and backoff across all status codes.
0 of 6. Every bad credential we sent to api.x.com/2 got the identical body title Unauthorized, detail Unauthorized; the auth-type mismatch came back as a separate 403 (15-request matrix, collected in 2026).
What a 401 means on the X API (and how it differs from 403)
HTTP 401 and 403 sit next to each other and get confused constantly. X's response-codes documentation draws the line clearly: 401 is "Invalid or missing authentication credentials", while 403 is "Valid auth but no permission for this resource or action". Put plainly, a 401 means the API never accepted who you are; a 403 means it accepted who you are and then refused what you asked for.
The v2 API returns errors in the problem-details shape: a title, a detail and a type URI. For most 4xx errors that combination is informative. For a 401 it is not. As the error matrix below shows, X returned {"title": "Unauthorized", "type": "about:blank", "status": 401, "detail": "Unauthorized"} for a missing header, a fake bearer token, a token without the Bearer scheme, an empty bearer value and two fake OAuth 1.0a headers. The response did carry an x-transaction-id header and content-type: application/problem+json, but no WWW-Authenticate header naming the scheme it expected.
That has one practical consequence: you cannot debug a 401 from the response alone. You debug it from the request you sent. Log the method, the full URL, and the Authorization header with the secret part masked, and compare that against what the endpoint requires.
The error matrix: 15 broken requests and exactly what came back
We sent 8 requests to api.x.com/2 and 7 to api.twitterapi.io, each with a deliberately broken credential: no header, a fake value such as Bearer invalid or invalid-test-key, an empty header, the key in the wrong header, and two fake OAuth 1.0a headers (one with a 2023 oauth_timestamp, one with the current time). No real key or token was used, so nothing was billed and no account was touched. Requests were spaced more than a second apart.
Reading the X rows. 6 of the 8 X requests came back 401 with the identical generic body. The two 403s are the interesting result: on GET /2/users/me and POST /2/tweets, X rejected the fake bearer token with Unsupported Authentication and the detail "Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint. Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0 User Context]." X checked the auth type before it checked whether the token was even valid. If your bearer token is fine and you call a user-context endpoint with it, this 403 is what you will see, not a 401.
The two OAuth 1.0a rows. A stale timestamp and a fresh timestamp produced the same 401 body. With fake consumer keys we cannot isolate clock skew, and the response gives no separate code for it, so treat the timestamp as one item on the checklist rather than something the API will name for you.
Reading the TwitterAPI.io rows. The service separates the two cases you most need to tell apart: 3 requests with no usable key returned 403 with API key required. Please include x-api-key in your request header, and 4 requests with a wrong key returned 401 API key is invalid. An Authorization: Bearer header was read as a key (it came back 401 invalid, not 403 missing), which matches the docs: Authorization: Bearer YOUR_API_KEY is accepted on REST endpoints, and if both headers are sent, x-api-key wins. A lower-case header name with a trailing space was read as a key too.

The causes of a Twitter API 401, in the order to check them
Because the body does not name the cause, work through the list from the quickest check to the most involved. Each item below is either documented by X or showed up in the public posts we classified.
1. The credential never arrived. An empty environment variable, a header set on the wrong object, or a redirect can strip it. A missing header returned the same 401 as a fake one in our test. Print the outgoing request and confirm the header is there. Call api.x.com directly rather than through a redirecting URL, since a client may drop the header on a cross-host redirect.
2. Whitespace, quotes or a truncated paste. A trailing newline from a .env file, quotes copied along with the value, or a token cut short by a terminal line wrap all produce a 401. One post we classified traced a day-long 401 hunt to a single extra space in a .env file. Call .strip() on every value you load.
3. Regenerated or revoked keys. X's first troubleshooting tip for 401 is "Ensure credentials haven't been regenerated". Regenerating the API key and secret, the bearer token, or the access token and secret in the developer console invalidates the old value. Any server, CI secret or teammate's script still holding the old one will start returning 401 the moment you click regenerate.
4. Keys from a different app or project. OAuth 1.0a needs four values that belong together: the consumer key and secret of one app, and an access token and secret generated for that same app. Mixing an access token from app A with consumer keys from app B fails signature checking. One Japanese-language post we classified described half a day lost to exactly this mismatch.
5. OAuth 1.0a signature or timestamp. X's OAuth 1.0a guide says oauth_timestamp must be the seconds since the Unix epoch when the request is generated and that "X will reject requests which were created too far in the past", and it recommends syncing the clock with NTP. Containers and virtual machines that were suspended are the usual offenders. Hand-built signatures also fail on percent-encoding: every parameter must be encoded before it is sorted and signed. Use a maintained library rather than signing by hand.
7. Expired OAuth 2.0 user tokens. X's docs say a user access token from the Authorization Code Flow with PKCE stays valid for two hours unless you used the offline.access scope, and that without that scope no refresh token is generated. A token that worked yesterday and fails today is usually expired, not broken. One post in our sample described exactly this pattern: a refresh that worked for days and then started failing with an invalid-token message.
8. App permissions changed after the token was issued. X's developer-apps page says "Changing permissions requires users to re-authorize your app to get new tokens with the updated scope." After switching to Read and Write, regenerate the access token and secret (or rerun the OAuth flow). Two classified posts hit this: reads worked, likes and DMs did not.
Fixing a 401 step by step: four commands that isolate it
These checks take about two minutes and split the problem into the credential itself, the auth type, and the environment. Run them from the same machine and shell the failing code runs in, so the same environment variables and clock are used.
Step 1: test the bearer token on an app-only endpoint. A 200 means the token is valid and the problem is elsewhere. A 401 means the token itself is wrong, revoked or regenerated.
Step 2: run the same token against a user-context endpoint. A 403 Unsupported Authentication here is expected and tells you that endpoint needs user credentials, not a better bearer token.
Step 3: inspect the raw bytes. od -c shows trailing \n, \r or quote characters that are invisible in a log line.
Step 4: check the clock if you sign OAuth 1.0a. Compare the Unix time against a trusted time source and enable NTP if it is off.
If all four pass and you still get 401 with OAuth 1.0a, regenerate the access token and secret for the same app, update every copy, and retry with a library that signs for you. If you use OAuth 2.0 user tokens, refresh the token and request offline.access next time so you can refresh automatically.
# 1) App-only bearer token: should return 200 with your token, 401 if the token is wrong
curl -s -o /dev/null -w "%{http_code}\n" \
-H "Authorization: Bearer $X_BEARER_TOKEN" \
"https://api.x.com/2/users/by/username/XDevelopers"
# 2) The same token on a user-context endpoint: 403 Unsupported Authentication is expected,
# because /2/users/me needs OAuth 1.0a or an OAuth 2.0 user token
curl -s -H "Authorization: Bearer $X_BEARER_TOKEN" "https://api.x.com/2/users/me"
# 3) Check the token has no hidden whitespace or quotes
printf '%s' "$X_BEARER_TOKEN" | od -c | tail -3
# 4) Clock check for OAuth 1.0a (compare to a trusted time source)
date -u +%stweepy 401 Unauthorized: Client vs API, and which credentials each call uses
tweepy maps HTTP status codes to exception classes: tweepy.errors.BadRequest (400), Unauthorized (401), Forbidden (403), NotFound (404), TooManyRequests (429) and TwitterServerError (5xx), all subclasses of HTTPException. Each exception carries response, api_errors, api_codes and api_messages, so log those instead of the bare string.
The tweepy.Client class (API v2) takes bearer_token, consumer_key, consumer_secret, access_token and access_token_secret. Which ones a call uses depends on its user_auth argument, documented as "Whether or not to use OAuth 1.0a User Context to authenticate". The defaults matter:
So a Client built with only bearer_token can read public data but cannot call get_me or create_tweet. A Client built with four OAuth 1.0a values but a bad access token secret fails on every user_auth=True call with tweepy.errors.Unauthorized, while bearer-token calls keep working, which looks confusing until you know the split. The older tweepy.API class targets the v1.1 endpoints; for API v2 use Client.
Several developers in our sample quoted the v1.1-era text Unauthorized: 401 Unauthorized 32 - Could not authenticate you. 5 of the 55 on-topic posts carried that code 32 message, all dated 2023, when many long-running bots started failing at once.
import os
import tweepy
client = tweepy.Client(
bearer_token=os.environ["X_BEARER_TOKEN"].strip(), # app-only: public reads
consumer_key=os.environ["X_API_KEY"].strip(), # OAuth 1.0a user context:
consumer_secret=os.environ["X_API_KEY_SECRET"].strip(), # needed by get_me, create_tweet,
access_token=os.environ["X_ACCESS_TOKEN"].strip(), # like, retweet, home timeline
access_token_secret=os.environ["X_ACCESS_TOKEN_SECRET"].strip(),
)
try:
me = client.get_me() # user_auth=True by default: uses the four OAuth 1.0a values
print("user context OK:", me.data.username)
u = client.get_user(username="XDevelopers") # user_auth=False by default: uses the bearer token
print("app-only OK:", u.data.id)
except tweepy.errors.Unauthorized as e: # HTTP 401: a credential was rejected
print("401", e.response.status_code, e.api_messages, e.api_codes)
except tweepy.errors.Forbidden as e: # HTTP 403: credential read, but wrong auth type, scope or access
print("403", e.api_messages)
What developers blame for a 401: a study of public posts
To see which causes actually bite, we searched public posts on X for "401" or "unauthorized" together with tweepy, "twitter api" or "x api" across six queries. The searches returned 334 posts, 187 unique. We read each one and kept 55 where a developer reported a 401 from the Twitter or X API (others were about unrelated APIs, security news, or reposts). Posts are dated 2009 to 2026; 31 are in English and 22 in Japanese.
22 of the 55 posts named no cause: the developer was stuck. Of the 33 that did, 13 suspected a change or outage on X's side and 20 named something on the client side.
The X-side cluster is mostly one year. 12 of the 13 posts suspecting an X-side change are dated 2023, when many bots and integrations started returning 401 at the same moment. That is a reminder to check X's status and developer announcements before rewriting your auth code when several apps break together.
On the client side, credentials dominate. Invalid, expired or mismatched keys and tokens were named in 5 posts, the largest client-side group; copy-paste problems, wrong auth type, app permissions and OAuth 1.0a signature or clock issues followed with two posts each. The smaller entries are worth knowing because they are hard to guess: a request rejected by network egress location, a request to a wrong URL, and a 401 when reading a deleted account's timeline.
The sample is small and the classification is ours, so read the shares as a ranking of what people run into, not as rates.

401 and 403 on TwitterAPI.io: one header, two answers
TwitterAPI.io is a separate REST API for X data: you authenticate with one API key, and reads need no X account, no developer app and no OAuth flow. That removes most of the causes above (no signature, no clock, no app-only vs user split for reads), but the key can still be missing or wrong, and the two cases return different codes.
The 401 and 403 rows are what we observed in the matrix; the 402 and 429 rows are as documented on docs.twitterapi.io/errors. Reset your key in the dashboard and every old copy starts returning 401, exactly like a regenerated X token. The full header reference, including the accepted Authorization: Bearer form, is on the x-api-key header page linked below.
Write actions (posting, liking, following) are a separate flow: one /twitter/user_login_v2 login ($0.10, with a proxy you supply) returns login_cookies, and each write such as /twitter/create_tweet_v2 is then 60 credits = $0.0006, billed per HTTP 200 call. The call acts as that account, so X can rate-limit, lock or suspend it; keep a human pace, and expect the session to need a re-login from time to time.
import os
import requests
BASE = "https://api.twitterapi.io"
API_KEY = os.environ.get("TWITTERAPI_IO_KEY", "").strip() # .strip() removes the stray space or newline that causes many 401s
def check_key(session):
"""Return None if the key works, else a readable reason. Uses one cheap profile lookup."""
r = session.get(f"{BASE}/twitter/user/info", params={"userName": "XDevelopers"}, timeout=30)
if r.status_code == 200:
return None
if r.status_code == 401:
return "401: the key was read but rejected (wrong, truncated or reset). Copy it again from the dashboard."
if r.status_code == 403:
return "403: no key reached the server. Check the header name (x-api-key) and that the variable is not empty."
if r.status_code == 402:
return "402: the key is valid but the account is out of credits."
return f"{r.status_code}: {r.text[:200]}"
def search(session, query, max_pages=3):
"""Yield tweets for a search, following next_cursor. Stops on any auth error instead of retrying it."""
cursor = ""
for _ in range(max_pages):
r = session.get(
f"{BASE}/twitter/tweet/advanced_search",
params={"query": query, "queryType": "Latest", "cursor": cursor},
timeout=30,
)
if r.status_code in (401, 403):
raise SystemExit(f"auth error {r.status_code}: {r.text[:200]}") # never retry an auth error
r.raise_for_status()
data = r.json()
for t in data.get("tweets", []):
yield t
if not data.get("has_next_page"):
break
cursor = data.get("next_cursor", "")
if __name__ == "__main__":
if not API_KEY:
raise SystemExit("TWITTERAPI_IO_KEY is empty: that request would come back 403")
s = requests.Session()
s.headers["X-API-Key"] = API_KEY
problem = check_key(s)
if problem:
raise SystemExit(problem)
for t in search(s, '"401" (tweepy OR "x api") -is:retweet', max_pages=2):
print(t["createdAt"], t["author"]["userName"], t["likeCount"], t["text"][:80].replace("\n", " "))
When the 401 is a sign to change how you read X data
Most 401s are a five-minute fix. But if your project only reads public posts and profiles, the official API's OAuth setup may be more machinery than the job needs. The cost side is the other half of the decision.
Per 1,000 tweets that is $5 against $0.15, about 33 times less on TwitterAPI.io, using X's published pay-per-usage rate card on docs.x.com/x-api/getting-started/pricing. X's pay-per-usage reads are capped at 3 million post reads a month, with Enterprise above that. On TwitterAPI.io you pay only for the data returned; a search that finds nothing is billed at the 15-credit minimum, $0.00015.
New accounts that pass the automatic bot check get up to $1 of free credits (at most 100,000 credits, no card, one per person or network, expiring after 31 days); purchased credits never expire. The rate limit is 0.2 requests per second before the first payment and 20 once paid. Subscriptions start at Starter $29/month; see the pricing page for the full list.
How we collected this
Question. What do the X API v2 and TwitterAPI.io return for missing, malformed or fake credentials, and what causes do developers report for Twitter or X API 401 errors?
Error matrix. 15 requests sent with curl in 2026: 8 to api.x.com/2 (/users/by/username/XDevelopers, /users/me, POST /tweets) and 7 to api.twitterapi.io (/twitter/user/info, /twitter/tweet/advanced_search, POST /twitter/create_tweet_v2). Only absent or obviously fake credentials were used, at least 1.2 seconds apart. We recorded status, content type, selected headers and the body verbatim.
Post study. Six searches through /twitter/tweet/advanced_search (Latest), 27 requests, 334 posts returned (187 unique), collected in 2026. Each post was read and placed in one cause category by hand; 55 were on topic. Study cost: $0.0501 in credits.
What the sample cannot show. Search returns what it ranks, not every post, so the post study is a convenience sample. People post about baffling failures more than quick fixes, which inflates "no cause" and "X-side" shares. With fake credentials we cannot tell whether X answers clock skew or a revoked token differently from a fake one at the signature level; we only know the body was identical in our tests.
Privacy. The post authors are private individuals: raw search pages were kept outside the repository, and we publish only aggregates and de-identified rows (category, year, language, counts) with no post IDs, URLs, text or handles.
import os
import requests
BASE = "https://api.twitterapi.io"
API_KEY = os.environ.get("TWITTERAPI_IO_KEY", "").strip() # .strip() removes the stray space or newline that causes many 401s
def check_key(session):
"""Return None if the key works, else a readable reason. Uses one cheap profile lookup."""
r = session.get(f"{BASE}/twitter/user/info", params={"userName": "XDevelopers"}, timeout=30)
if r.status_code == 200:
return None
if r.status_code == 401:
return "401: the key was read but rejected (wrong, truncated or reset). Copy it again from the dashboard."
if r.status_code == 403:
return "403: no key reached the server. Check the header name (x-api-key) and that the variable is not empty."
if r.status_code == 402:
return "402: the key is valid but the account is out of credits."
return f"{r.status_code}: {r.text[:200]}"
def search(session, query, max_pages=3):
"""Yield tweets for a search, following next_cursor. Stops on any auth error instead of retrying it."""
cursor = ""
for _ in range(max_pages):
r = session.get(
f"{BASE}/twitter/tweet/advanced_search",
params={"query": query, "queryType": "Latest", "cursor": cursor},
timeout=30,
)
if r.status_code in (401, 403):
raise SystemExit(f"auth error {r.status_code}: {r.text[:200]}") # never retry an auth error
r.raise_for_status()
data = r.json()
for t in data.get("tweets", []):
yield t
if not data.get("has_next_page"):
break
cursor = data.get("next_cursor", "")
if __name__ == "__main__":
if not API_KEY:
raise SystemExit("TWITTERAPI_IO_KEY is empty: that request would come back 403")
s = requests.Session()
s.headers["X-API-Key"] = API_KEY
problem = check_key(s)
if problem:
raise SystemExit(problem)
for t in search(s, '"401" (tweepy OR "x api") -is:retweet', max_pages=2):
print(t["createdAt"], t["author"]["userName"], t["likeCount"], t["text"][:80].replace("\n", " "))
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
What does 401 Unauthorized mean on the Twitter (X) API?
X defines 401 as "Invalid or missing authentication credentials". The request reached the API but the credential was absent, malformed, wrong, revoked, regenerated, or (for OAuth 1.0a) failed signature or timestamp checks. It does not mean your plan lacks access to the endpoint; that is a 403.
What is the difference between a 401 and a 403 on the X API?
A 401 means the API did not accept your credential at all. A 403 means it accepted the credential and refused the request: wrong auth type, missing scopes, missing app permission or no access to that endpoint. In our test an app-only bearer token sent to /2/users/me returned 403 Unsupported Authentication, not 401.
Why do I get tweepy.errors.Unauthorized 401?
tweepy raises Unauthorized for any HTTP 401. With tweepy.Client, methods like get_me and create_tweet default to user_auth=True and sign with consumer_key, consumer_secret, access_token and access_token_secret, so one wrong or stale value among those four fails those calls while bearer-token calls keep working. Strip whitespace, regenerate the access token after any permission change, and make sure all four values come from the same app.
My token worked yesterday and now returns 401. Why?
Someone (or a script) most likely regenerated it in the developer console, which invalidates the old value everywhere. Update every copy: servers, CI secrets, .env files. If it is an OAuth 2.0 user access token rather than an app-only bearer token, it has probably expired: X's docs say these stay valid for two hours unless you used the offline.access scope, which is also what gets you a refresh token.
Can clock skew cause a 401 on the X API?
Yes, for OAuth 1.0a. X's docs say oauth_timestamp must be the request time in Unix seconds and that X rejects requests created too far in the past. Sync the clock with NTP, especially on containers or virtual machines that were suspended. In our test the 401 body looked the same for an old and a current timestamp, so the response will not tell you it was the clock.
Why does POST /2/tweets fail even though my keys are correct?
Posting needs user context: OAuth 1.0a User Context or an OAuth 2.0 user access token with the tweet.write scope. An app-only bearer token is refused with 403 Unsupported Authentication. If you use OAuth 1.0a and recently changed the app to Read and Write, regenerate the access token and secret, because existing tokens keep the old permission.
What does a 401 from TwitterAPI.io mean?
It means a key reached the server but was not valid: wrong, truncated, or reset in the dashboard. A request with no x-api-key header (or an empty one) returns 403 with API key required instead. Copy the key again from the dashboard and strip whitespace when you load it.
Should my code retry a 401?
No. A 401 will not fix itself on retry, and repeated failing requests just fill your logs. Stop, log the masked request, alert, and fix the credential. Retry with backoff only for 429 and 5xx responses.
Continue
- X developer docs: Response codes and errors (401 and 403 definitions, problem types)
- X developer docs: Authentication overview (OAuth 1.0a User Context, app-only, OAuth 2.0 PKCE)
- X developer docs: Authorizing an OAuth 1.0a request (oauth_timestamp, nonce, signature)
- tweepy docs: Exceptions (Unauthorized, Forbidden, HTTPException attributes)
- tweepy docs: Client (credentials and user_auth defaults)
- TwitterAPI.io docs: Authentication (x-api-key header, Bearer alternative, 401 vs 403)
- X API overview: endpoints, pricing and access
- X API 403 Forbidden: every cause and fix
- Twitter (X) API error 400 Bad Request explained
- Twitter (X) API error handling: retries, backoff and status codes
- The x-api-key header: how to send your API key
- Twitter access tokens: how to get and use them
- TwitterAPI.io pricing: $0.15 per 1,000 tweets returned
- 01PhantomBuster Pricing: Plans, Execution Hours and What X (Twitter) Data Really Costs
- 02Sprinklr Pricing: What It Costs Now That Self-Serve Has Ended
- 03Goose MCP: How to Add MCP Servers (Extensions) to goose, Desktop and CLI
- 04ChatGPT Apps SDK Tutorial: Build a ChatGPT App That Answers With Live Twitter (X) Data
- 05LM Studio MCP: Connect MCP Servers (and Live Twitter (X) Data) to a Local Model
- 06Tweet Character Count — Limits and How Counting Really Works
- 07How Do You Turn On Twitter (X) Dark Mode, and What Are Its Exact Colors?
- 08SOCMINT on Twitter (X): What Social Media Intelligence Is, and a Worked Method
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.