X API 402 Payment Required: What It Means on Twitter (X) Pay-Per-Use and How to Fix It

By TwitterAPI.io Team•13 min read
Decision tree for an X API 402 Payment Required error: check balance, then which app the keys belong to, then the spending limit, then report
The four checks for an X API 402, in order. Shares from public posts collected in 2026.
TL;DR
  • 402 on the X API = no spendable credits. X's pay-per-use model bills each call against a prepaid balance; when it reaches zero (or goes slightly negative) billable requests are blocked until you add credits.
  • Two body shapes in the wild: title: "CreditsDepleted" with "Your enrolled account ... does not have any credits", or title: "Payment Required", detail: "credits depleted", type: .../problems/credits-depleted. X's error reference page does not list 402 at all.
  • Check in order: balance (GET /2/usage/credits, total_balance), then which app the keys belong to, then the billing-cycle spending limit, then a fresh top-up that has not applied yet.
  • What developers hit: of 42 on-topic public posts collected in 2026, 57.1% said the balance ran out, 31% expected free access, and 57.1% of failing calls involved posting.
  • Never retry a 402. Treat it like a 401: stop the job, alert a human, and resume only after the balance is positive. A retry loop just burns rate-limit headroom.
  • On TwitterAPI.io the same state returns HTTP 402 with "message": "Credits is not enough.Please recharge"; GET /oapi/my/info returns recharge_credits, tweets cost $0.15 per 1,000 returned, and purchased credits never expire.

Since X launched pay-per-use for the X API on 6 February 2026, every billable call draws from a prepaid credit balance. When that balance is empty, the API answers with HTTP 402 Payment Required. The code is rare across the web, so the message surprises people: a posting bot that worked for years stops overnight, or a brand-new app fails on its first request after OAuth finally works.

This guide covers the 402 that api.x.com returns for credits. It is not about the x402 payment protocol, which reuses the same status code so that AI agents can pay per request in stablecoins; if that is what you are building, read the x402 explainer linked at the end of this page instead.

Below: the exact error bodies developers have posted, what X's own docs do and do not say, a fix checklist in the order that resolves the majority of cases, a balance pre-check you can paste into a batch job, and a study of public posts about the error. The same pattern on TwitterAPI.io is covered at the end.

of public X API 402 posts say the credit balance simply ran out

57.1%

01 — Section

What a 402 from the X API means

HTTP 402 is defined in RFC 9110 as "reserved for future use", so each API that uses it defines its own meaning. On the X API it means one thing: the developer account that owns the calling app cannot pay for the request. X's pricing page describes the model plainly: you buy credits up front in the Developer Console, they are "deducted as you use the API", and when a balance goes slightly negative "API requests will be blocked until you add credits to cover the negative balance".

X staff answering on the developer forum (devcommunity.x.com) say the same in short form: a 402 "Credits Depleted" is "expected when balance hits zero", and "the 402 means your prepaid credit balance is depleted ($0 remaining)".

What 402 is not. It is not an authentication failure (that is 401), not a permission or enrollment problem on a specific endpoint (403), and not a rate or volume limit. X's own error reference lists 429 for "Rate limit or usage cap exceeded", which covers the 3 million post reads per month cap on pay-per-use. If you see 429 you have too much traffic; if you see 402 you have too little money.

Which calls fail. Only billable calls. Developers on the forum report that GET /2/users/me keeps returning 200 with the same token while billable reads such as search, followers and bookmarks return 402, which is a useful tell: if users/me works and everything else returns 402, your auth is fine and the problem is billing.

02 — Section

The exact X API 402 error bodies

X's Response Codes & Errors page at docs.x.com/x-api/fundamentals/response-codes-and-errors lists 400, 401, 403, 404, 409 and 429 but has no row for 402, and the published OpenAPI spec (api.x.com/2/openapi.json) defines no credits problem type. So the body below comes from what developers have pasted on X's forum and in public posts, not from a documented schema. Two shapes appear:

ShapetitledetailOther fields
A (older, still seen)CreditsDepletedYour enrolled account [account id] does not have any credits to fulfill this request.account_id, type (sometimes empty)
B (problem+json style)Payment Requiredcredits depletedtype: https://api.x.com/2/problems/credits-depleted, status: 402

Match both. Client libraries wrap the body differently: in the posts we collected, Python bots logged HTTPException: 402 Payment Required followed by the detail, and JavaScript bots logged Request failed with code 402 followed by the title. Branch on the HTTP status first, then look for CreditsDepleted or credits-depleted / credits depleted in the body, as in the code below.

python
import requests


def is_x_credits_error(resp: requests.Response) -> bool:
    """True when api.x.com refused a call because the account has no credits."""
    if resp.status_code != 402:
        return False
    try:
        body = resp.json()
    except ValueError:
        return True  # a 402 from api.x.com is a billing state either way
    title = str(body.get("title", ""))
    detail = str(body.get("detail", "")).lower()
    kind = str(body.get("type", ""))
    return (
        title in ("CreditsDepleted", "Payment Required")
        or "credits depleted" in detail
        or "does not have any credits" in detail
        or kind.endswith("/credits-depleted")
    )
03 — Section

Fix checklist: four checks in order

Work down the table. Each row is cheap to check and the earlier rows resolve the majority of reports.

StepCheckWhereIf true, do this
1Balance is 0 or negativeGET /2/usage/credits (total_balance, prepaid_balance) or Console > BillingBuy credits. Auto-recharge does not run at zero or below, so top up by hand once.
2Keys belong to another app or accountConsole: which account owns the App ID your token was issued forUse the funded app's keys or OAuth client, then re-authorize users.
3Billing-cycle spending limit reachedConsole > Billing > spending limitRaise the limit or wait for the next cycle.
4Balance positive, keys right, no capA top-up made minutes agoWait a few minutes and retry once; then post App ID, endpoint and request time on devcommunity.x.com.

Step 1 detail. GET /2/usage/credits returns total_balance, which X defines as max(0, prepaid_balance + free_balance), plus prepaid_balance (which "may be negative"), free_balance and free_grants. If total_balance is 0, the 402 is fully explained. Free incentive credits are spent before purchased credits and expire; our X API voucher guide covers those rules.

Step 2 detail. This is the classic "I have $20 and still get 402" case. In one forum thread the developer's job was using an OAuth 2.0 client from an older developer account with no credits; switching to the funded app's client ID and re-authorizing ended the 402. In another, X staff found the App ID was owned by a different account whose balance was negative. X's multi-account Developer Console (personal plus team accounts, each with its own billing) makes this easier to get wrong.

Step 3 detail. X's pricing page says that when a spending limit is reached "API requests will be blocked until the next billing cycle". The page does not state which status code that block returns, so treat this as a likely cause rather than a confirmed 402 body. A limit is not money: X staff point out that a cap "limits spend but doesn't fund it", so a high cap with a $0 balance still returns 402.

Step 4 detail. X staff note that "top-ups sometimes have a short delay before applying", and that auto-recharge checks run hourly and need a valid default payment method with no failed charges. If a manual purchase receipt arrived and the 402 persists well past that, it is an account-side problem only X can fix.

04 — Section

Why developers hit it: a study of public posts

We searched public X posts for the error with eight queries (for example "402" ("x api" OR "twitter api"), CreditsDepleted OR "credits depleted" and "does not have any credits"). After de-duplication and removing exact copies, 499 unique posts remained; 42 of them (8.4%) were about an X API 402. The rest were about the x402 protocol, other AI APIs' billing errors, or unrelated uses of the number 402. Each on-topic post was classified from its text by keyword rules.

Cause describedPostsShare
Balance ran out (credits used up)2457.1%
Expected free access (old Free tier, hobby bot)1331%
Error quoted, no cause given37.1%
Paid, but balance not updated yet24.8%

Posting bots take the hit. 57.1% of on-topic posts described a failing post or reply (alone or together with reads); only 4.8% described reads alone, and 38.1% did not say. Many are small, long-running bots (weather, exchange rates, birthdays, daily data) whose owners had never paid for API access before.

It is not only English. 40.5% of on-topic posts were in other languages, 13 of 42 in Japanese alone, which matches the large Japanese hobby-bot scene. 35.7% pasted X's CreditsDepleted / "does not have any credits" wording verbatim, which is why that phrase is worth matching in logs.

Bar charts: causes of X API 402 errors described in 42 public posts, and which call failed
Causes and failing call types in 42 public X posts about X API 402 errors, collected in 2026.
05 — Section

How X's credit model got here

The spike in 402 reports follows a sequence of announcements from @XDevelopers, X's official developer account. Each one moved a group of apps onto prepaid credits:

WhenWhat @XDevelopers announcedEffect on 402s
October 20, 2025Closed beta of the pay-per-use modelFirst apps on prepaid credits
6 February 2026Pay-per-use launch; legacy Free users move to pay-per-use with a one-time voucherFree-tier bots start failing once the voucher is spent
May 21, 2026Legacy Basic plans deprecated; subscribers migrated to pay-per-use after June 1, 2026Former Basic apps need a funded balance
October 2, 2026New pay-per-use accounts get up to $70 in free credits ($20 + first auto-recharge matched up to $50)Fewer zero-balance first calls, once the account qualifies

The free-credit page on docs.x.com now says the $20 lands after an account with its first eligible card completes its first purchase of API credits, and that incentive credits expire three months after they are granted. The forum and public posts in our sample show the practical consequence: a bot that ran for years on the Free tier keeps working on a voucher or free grant, then starts returning 402 the day that grant runs out.

06 — Section

Prevent it: check the balance before every batch

A 402 in the middle of a job is the expensive way to learn your balance. X exposes two usage endpoints: GET /2/usage/credits for the dollar balance and GET /2/usage/tweets for daily post consumption counts. /2/usage/credits accepts an app Bearer token. Read the balance before a batch, estimate what the batch will cost at X's rate card ($0.005 per post read, $0.010 per user read, $0.015 per post created, $0.20 per post created with a URL), and refuse to start when the balance cannot cover it.

Turn on auto-recharge, but do not rely on it alone. X's docs say auto-recharge triggers the first time the balance drops below your threshold after being at or above it, and that it is paused while the balance is zero or negative. If one run overdraws the balance, auto-recharge will not rescue it; a manual purchase is needed first.

Set a spending limit that matches your budget, and an alert below it. The Console offers balance alerts; pair them with the pre-check below so a job stops itself instead of paging you with 402s.

Watch posting costs with links. At $0.20 per post that contains a URL against $0.015 without one, a link-heavy posting bot drains a balance roughly 13 times faster; X staff made the same point on the forum to a developer whose balance ran out.

python
import os
import sys

import requests

X_BEARER = os.environ["X_BEARER_TOKEN"]
POST_READ_USD = 0.005  # X pay-per-use rate card, per post read


def x_balance_usd() -> float:
    r = requests.get(
        "https://api.x.com/2/usage/credits",
        headers={"Authorization": f"Bearer {X_BEARER}"},
        timeout=30,
    )
    r.raise_for_status()
    data = r.json()["data"]
    # total_balance = max(0, prepaid_balance + free_balance) per docs.x.com
    return float(data["total_balance"])


def preflight(posts_to_read: int, margin: float = 1.2) -> None:
    need = posts_to_read * POST_READ_USD * margin
    have = x_balance_usd()
    if have < need:
        sys.exit(f"Stop: batch needs about ${need:.2f}, balance is ${have:.2f}. Top up first.")
    print(f"OK: ${have:.2f} available, batch needs about ${need:.2f}")


if __name__ == "__main__":
    preflight(posts_to_read=5_000)
07 — Section

Handle 402 in code: stop, do not retry

A 402 is terminal for the current run. Retrying it cannot succeed until a human adds credits, and a loop that polls every few seconds just fills logs. In our sample, a developer described a scheduler that treated each 402 as a problem with one post and moved on, losing several posts overnight; another described a read client that kept hitting an empty credit pool on every tick until they added a pause layer.

The rule: retry 429 and 5xx with backoff; never retry 400, 401, 402 or 403. On a 402, stop the queue, persist what has not been sent, alert, and resume only after the balance check passes again.

StatusMeaning on the X APIRetry?
401Bad or missing credentialsNo: fix the token
402No spendable credits (CreditsDepleted)No: add credits, check the app
403Not permitted for this resource or appNo: fix access or enrollment
429Rate limit or monthly usage capYes: after the reset or next cycle
5xxServer errorYes: exponential backoff
08 — Section

What happens on TwitterAPI.io when credits run out

TwitterAPI.io is a separate pay-as-you-go API for X data, and it uses the same status code for the same reason. Per docs.twitterapi.io/errors, an account that is out of credits gets HTTP 402 with the body {"error": "Unauthorized", "message": "Credits is not enough.Please recharge"}. The docs are blunt about the fix: stop retrying and top up on the dashboard. The remaining balance is available at GET /oapi/my/info as recharge_credits, which is the equivalent of X's /2/usage/credits pre-check.

Official X API (pay-per-use rate card)TwitterAPI.io
Reading 1,000 tweets$5.00 ($0.005 per post read)$0.15 (15 credits per tweet returned)
Out-of-credits status402, CreditsDepleted / credits-depleted402, Credits is not enough.Please recharge
Balance endpointGET /2/usage/creditsGET /oapi/my/info
Credit expiryPurchased: no; incentive grants: 3 monthsPurchased: never
Account needed to readX developer account + appAPI key only, no X account needed

At X's $5 per 1,000 post reads against $0.15 per 1,000 tweets here, the read price differs by about 33x. New TwitterAPI.io accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); see the pricing page for the amount. Rate limits are 0.2 requests per second before the first payment and 20 once paid.

Writes are a different product here. Posting through TwitterAPI.io runs through an authenticated session: one /twitter/user_login_v2 login ($0.10, with a proxy you supply) returns login_cookies, and each post through /twitter/create_tweet_v2 is then 60 credits ($0.0006). The call acts as that account, so X can rate-limit, lock or suspend it; keep a human pace, expect the session to need a re-login sometimes, and note that every HTTP 200 call is billed.

09 — Section

How we collected this

Question. When developers post publicly on X about a 402 / Payment Required / CreditsDepleted error from the X API, what cause do they describe and which call failed?

Queries. Eight advanced_search queries through our own API (Latest, plus one Top): the status code with "x api" / "twitter api", "Payment Required" with api / xdk, CreditsDepleted and "credits depleted", X's "does not have any credits" wording, "out of credits" with X API terms, and a separate query over @XDevelopers posts about credits and pay-per-use for the timeline.

Sample. 875 posts returned in 54 requests, 499 unique after de-duplication, 42 on-topic, collected in 2026. Search returns what X indexes, not every post ever written, so counts are a sample, not a census.

What it cannot show. How often 402 happens across all X API apps; the keyword classifier can miss sarcasm or misfile a post that mentions two causes; posts that only say "my bot stopped" without the error text are not captured.

Privacy. Aggregates only. The authors of topic-search posts are private individuals: their raw posts stayed out of the published dataset, and the de-identified sample has no ids, handles, links or text. Only @XDevelopers, an organization account, is named.

python
"""Batch search with a balance pre-check and a hard stop on 402 (TwitterAPI.io)."""
import os
import sys
import time

import requests

BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
CREDITS_PER_TWEET = 15  # $0.15 per 1,000 tweets returned


class OutOfCredits(Exception):
    pass


def get(url, params=None, attempts=5):
    for i in range(attempts):
        r = requests.get(url, params=params, headers=HEADERS, timeout=30)
        if r.status_code == 402:
            raise OutOfCredits(r.json().get("message", "Credits is not enough"))
        if r.status_code in (429, 500, 502, 503):
            time.sleep(2 ** i)
            continue
        r.raise_for_status()
        return r.json()
    raise RuntimeError("gave up after retries")


def remaining_credits() -> int:
    return int(get(f"{BASE}/oapi/my/info").get("recharge_credits", 0))


def search(query: str, max_tweets: int):
    need = max_tweets * CREDITS_PER_TWEET
    have = remaining_credits()
    if have < need:
        sys.exit(f"Stop: need about {need:,} credits, have {have:,}. Top up first.")

    tweets, cursor = [], ""
    while len(tweets) < max_tweets:
        params = {"query": query, "queryType": "Latest"}
        if cursor:
            params["cursor"] = cursor
        try:
            page = get(f"{BASE}/twitter/tweet/advanced_search", params)
        except OutOfCredits as err:
            print(f"402: {err}. Saving {len(tweets)} tweets and stopping.")
            break
        for t in page.get("tweets", []):
            tweets.append({
                "id": t["id"],
                "createdAt": t["createdAt"],
                "author": t["author"]["userName"],
                "likes": t.get("likeCount", 0),
                "text": t["text"],
            })
        if not page.get("has_next_page"):
            break
        cursor = page.get("next_cursor", "")
    return tweets[:max_tweets]


if __name__ == "__main__":
    rows = search('"x api" 402 -is:retweet', max_tweets=200)
    print(len(rows), "tweets")

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

What does 402 Payment Required mean on the X API?

It means the developer account that owns your app has no spendable pay-per-use credits. X bills each billable call against a prepaid balance; at zero (or slightly negative) it blocks those calls with HTTP 402 until you add credits. Developers see title: "CreditsDepleted" or title: "Payment Required" with detail: "credits depleted".

Why do I get 402 CreditsDepleted when my console shows credits?

Usually the keys or OAuth client you call with belong to a different app or developer account than the funded one. Check which account owns the App ID, switch to that app's keys and re-authorize. If the keys are right, check the billing-cycle spending limit and give a fresh top-up a few minutes to apply.

Is the X API Free tier gone?

For the majority of developers, yes. X's launch post for pay-per-use (6 February 2026) said legacy Free users move to pay-per-use with a one-time voucher, and only for-good Public Utility apps keep free scaled access. Once that voucher or any free grant is spent, billable calls return 402. See our X API voucher guide for the current free-credit rules.

Does auto-recharge fix a 402 automatically?

Not if the balance already hit zero or went negative. docs.x.com says auto-recharge does not run while the balance is zero or negative, so you need one manual purchase first. X staff also say the recharge check runs hourly and needs a valid default payment method.

How do I check my X API credit balance from code?

Call GET https://api.x.com/2/usage/credits with your app's Bearer token. It returns total_balance (spendable, clamped at 0), prepaid_balance (can be negative), free_balance and free_grants. GET /2/usage/tweets returns daily post consumption counts.

Should I retry a request that returned 402?

No. A 402 is a billing state, not a transient error, so a retry fails the same way. Stop the job, alert, add credits or fix the app, and resume after a balance check passes. Retry only 429 and 5xx responses, with backoff.

Is the X API 402 related to the x402 protocol?

No. x402 is an open payment protocol that uses the HTTP 402 status code so clients such as AI agents can pay per request, typically in stablecoins. The X API's 402 is an ordinary account-billing error from X's pay-per-use system.

What does TwitterAPI.io return when credits run out?

HTTP 402 with {"error": "Unauthorized", "message": "Credits is not enough.Please recharge"}, per docs.twitterapi.io. Check the balance first with GET /oapi/my/info (recharge_credits), stop on 402, and top up on the dashboard. Purchased credits never expire.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.