Skip to content
Twexapi
English
Esc
↑↓navigate↵open⌘Jpreview
On this page

Error Handling

Recover from TwexAPI HTTP errors, MCP tool failures, credit limits, and write-action retries.

TwexAPI returns errors at two layers: MCP JSON-RPC errors (authentication before a tool runs) and REST HTTP errors (after a request reaches the API). Preserve status codes, response bodies, cursors, and IDs so retries and human review stay safe.

REST response envelope

Successful calls return:

{
  "code": 200,
  "msg": "success",
  "data": {}
}

When HTTP status is not 2xx, treat the response as a failure even if the body includes a code field. Log the full body, the request path, and any cursor you already consumed.

HTTP status recovery

Status Meaning Action
400 Invalid query, missing field, or malformed body Fix input. Do not retry unchanged.
401 Missing or invalid API key Replace the credential from the dashboard. Check Authorization: Bearer formatting.
403 Credits exhausted, account restricted, or action not allowed Check Get Balance. Top up or remove write steps until access returns.
404 Tweet, user, list, or resource not found Verify IDs, screen names, and cursor freshness.
422 Validation failed on structured input Fix schema fields documented on the endpoint page. Do not retry unchanged.
429 Rate limit exceeded Back off using Rate Limits. Preserve next_cursor and completed rows.
5xx Transient service or upstream fetch failure Retry with exponential backoff and a hard cap.

Credits and balance

Metered reads and writes spend account credits. When a job processes many pages, check balance before and after long runs:

curl --request GET \
  --url 'https://api.twexapi.io/balance' \
  --header 'Authorization: Bearer YOUR_API_KEY'

If 403 responses mention credits or access:

  1. Stop scheduled jobs that keep hammering the API.
  2. Confirm balance in the dashboard.
  3. Resume from the last saved cursor after credits are restored.

Pagination-safe retries

For search, followers, timelines, and DM history:

  • Store next_cursor, has_next_page, and any task_id outside the agent conversation.
  • After 429 or 5xx, retry the same cursor, not the next page.
  • After 400, 404, or 422, inspect IDs and query parameters before retrying.

Write actions

Write endpoints (tweet, reply, like, follow, DM send) require:

  • A valid TwexAPI API key
  • A saved Twitter cookie or auth_token on the request

Recovery rules:

Situation Action
401 on write Fix API key and cookie credentials before retrying.
403 on write Confirm credits and that the connected account still has permission.
Ambiguous success Look up the tweet, DM, or engagement state with a read endpoint before duplicating the action.
Agent workflows Require human approval before any read_only: false MCP call.

Prefer idempotent read checks (tweet lookup, profile about) before repeating requests. See Rate Limits for backoff.

Retry tweet posts safely with an Idempotency-Key

POST /twitter/tweets/create and POST /twitter/tweets/quote accept an optional Idempotency-Key header. Send a new value for each post, such as a UUID, and send the same value again when you retry that post after a timeout or network error:

curl https://api.twexapi.io/twitter/tweets/create \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 8f14e45f-ceea-467f-a8d1-1f0b4c2a9e01" \
  -d '{"cookie": "auth_token=...; ct0=...", "tweet_content": "Hello from TwexAPI"}'
Retry with the same key Result
The first request succeeded (within 24 hours) Returns the first response with the header Idempotent-Replayed: true. Nothing is posted again and no credits are charged.
The first request is still running 409. Wait a moment, then retry with the same key.
The body is different 422. Use a new key for a different post.
The first request failed Runs again. Failed requests do not keep the key.

Keys are 1 to 255 visible ASCII characters and are scoped to your API key. Without the header, every request posts. MCP twexapi_write calls send a key automatically: repeating the exact same call within 10 minutes returns the first result.

MCP errors

Authentication failed before the tool ran

When MCP authentication fails, no tool runs:

{
  "jsonrpc": "2.0",
  "id": null,
  "error": {
    "code": 401,
    "message": "Access token is invalid or expired"
  }
}

Sign in again from the MCP client, or fix x-api-key or Authorization: Bearer, then rerun the tool call. See the MCP tools reference for every authentication message.

No credits left

When the account has no credits, the MCP connection still works and explore is free, but other tool calls return an error result without calling the API:

{
  "error": "No credits left on this TwexAPI account. Top up at https://twexapi.io/dashboard and try again."
}

Stop and ask the user to top up; retrying does not help.

API error returned through twexapi_request or twexapi_write

When the underlying REST call fails, preserve the tool result:

{
  "status_code": 429,
  "endpoint": "get_global_trending_tweets",
  "method": "GET",
  "path": "/twitter/global-trending/tweets",
  "result": {
    "code": 429,
    "msg": "Rate limit exceeded. QPS limit: 2 requests per second",
    "data": []
  }
}

Apply the same HTTP recovery table above. Do not ask the model to guess a new path—call explore again if the route may have changed.

SDK and CLI errors

Generated SDKs map HTTP failures to language-native exceptions. Catch errors at the job boundary, log the status code and response body, and route 429/5xx to retry policies.

Python example:

import requests

try:
    response = requests.get(
        "https://api.twexapi.io/balance",
        headers={"Authorization": "Bearer YOUR_API_KEY"},
        timeout=30,
    )
    response.raise_for_status()
except requests.HTTPError as exc:
    status = exc.response.status_code
    body = exc.response.text
    if status == 429:
        # Back off, preserve cursor, retry later
        ...
    elif status in (400, 404, 422):
        # Fix input; do not retry unchanged
        ...
    raise

See language-specific patterns on each SDK page.

Retry backoff template

Use capped exponential backoff for 429 and 5xx:

retry_delays_seconds = [5, 15, 45, 120]

for delay in retry_delays_seconds:
    response = call_twexapi()
    if response.ok:
        break
    if response.status_code in (429, 500, 502, 503, 504):
        time.sleep(delay)
        continue
    break  # 4xx other than 429: stop and fix input

Pair backoff with Rate Limits so scheduled jobs do not restart at full QPS immediately after a 429.

Framework-specific notes

Runtime Guidance
LangChain Validate handoff models; stop the graph on 401.
Prefect Use task retries with jitter; store cursors in task state.
n8n / Zapier / Make Route 401/403 to ops alerts; delay 429 replays.
MCP agents Never discard next_cursor after partial success.

Was this page helpful?