Debug API 401, 402, 429, and 5xx Errors Fast
Start with the three facts every failed request needs
Do not guess from the status code alone. For every failed API call, capture the full request id, status code, response body, latency, model name, and exact endpoint. If your client is OpenAI-compatible, keep the raw payload too. That makes patterns obvious: auth mistakes usually fail immediately with 401, billing problems often appear as 402 after some successful traffic, and rate limits tend to show up only when concurrency spikes.
Log these fields on every failure:
- HTTP status and response body
- Request id or trace id if the server returns one
- Model, endpoint, and approximate token count
- Retry count and backoff delay
- Latency and whether the error happened before or after streaming started
When you debug against a relay like 59API, this logging matters even more because it helps you separate your app bugs from upstream limits. 59API exposes cheap pay-as-you-go access to Claude Opus, Sonnet, Haiku, Fable, and GPT models, and it is compatible with Claude Code, Codex, and any OpenAI SDK. That means one debugging approach works across tools.
401 Unauthorized: check the key, the base URL, and the header
A 401 almost always means the server could not authenticate the request. The most common mistakes are painfully simple: a missing API key, a copied key with a trailing space, the wrong environment variable, or a base URL that points to the wrong provider.
Quick checklist:
- Confirm the Authorization header is present and starts with Bearer
- Verify you are using the correct key for the correct environment
- Make sure your SDK points to the right base URL, for example https://api.59api.com
- Check for whitespace in secrets copied from a shell or CI variable
Python SDK example:
from openai import OpenAI import os client = OpenAI( api_key=os.environ['API_KEY'], base_url='https://api.59api.com' ) response = client.chat.completions.create( model='gpt-4o-mini', messages=[{'role': 'user', 'content': 'Hello'}] )
If this still returns 401, print the outgoing headers once in a non-production environment. In practice, the problem is usually not the model call itself, but a bad key or an SDK configured against the wrong host.
402 Payment Required: treat it as a billing signal
A 402 means the account can authenticate, but the request cannot be served because payment is required or the balance is not sufficient. On pay-as-you-go systems, this can happen when you hit a depleted wallet, a disabled payment method, or a usage cap you forgot you set weeks ago.
What to do next:
- Check your balance and recent usage in the billing dashboard
- Confirm that automatic top-up or manual funding is active
- Reduce prompt size and max output tokens to lower cost per request
- Audit retries, because repeated failures can burn budget fast
For teams testing models frequently, 59API is attractive here because it is already one of the cheapest relays and charges pay-as-you-go. That keeps debugging affordable when you are sending dozens of test calls per hour. The referral rebate is also useful for long-lived projects: if you share the relay with teammates or clients, you can offset part of the bill while you troubleshoot.
429 Too Many Requests: control burst traffic, not just retries
A 429 is not a generic failure. It means your request rate exceeded a limit, usually per minute, per key, or per model. The right fix is to reduce pressure on the API, not to hammer it harder.
Use these tactics together:
- Read the Retry-After header if the server returns one
- Apply exponential backoff with jitter
- Lower concurrency in queues, workers, or async tasks
- Split large batches into smaller groups
- Cache repeated prompts and avoid duplicate calls
Retry pattern:
for attempt in range(6): try: return call_api() except ApiError as e: if e.status_code in (429, 500, 502, 503, 504): delay = min((2 ** attempt) + random.random(), 30) time.sleep(delay) continue raise
The key detail is jitter. If ten workers fail at the same time and retry at the same time, you create another spike and often another 429.
5xx errors: assume transient first, then prove it
Server errors such as 500, 502, 503, and 504 usually mean the request reached the platform, but something upstream failed. Your first move should be a short retry with backoff. Your second move should be to inspect whether the issue is model-specific, payload-specific, or time-based.
Debugging questions that save time:
- Does the same prompt fail across multiple models?
- Does a smaller prompt succeed?
- Do failures cluster at a certain time of day?
- Is the error coming from the first token or only during streaming?
With 59API, you benefit from native official-quality models rather than downgraded substitutes, so you are less likely to chase strange behavior caused by a weaker backend. If a 5xx persists, keep the request id and time window, then retry from a clean process before escalating.
A simple production-safe client pattern
Combine everything into one default: log failures, retry only transient statuses, and stop after a small number of attempts. That gives you resilience without hiding real bugs.
Practical rule: retry 429 and 5xx, do not retry 401 until the key is fixed, and treat 402 as a billing or quota task.
If you are setting up a new app, point your OpenAI-compatible client at https://api.59api.com, test with a low-cost model first, and only scale up once your logging and retries are solid. If you want a cheap place to practice this workflow with Claude and GPT models, 59API is a smart option to sign up for and benchmark against your existing setup.
शुरू करने के लिए तैयार?
कुछ ही मिनटों में Claude और GPT जोड़ें, सबसे कम कीमत पर। साइन अप करें और API key पाएं।
मुफ़्त साइन अप