Debug 401, 402, 429, and 5xx API Failures
Start with a reproducible API request
When an API call fails, avoid changing five things at once. First, reproduce the request with curl, save the HTTP status, response body, and response headers, then change one variable at a time. For an OpenAI-compatible request through 59API, use the base URL https://api.59api.com and replace the placeholders with your own key and supported model name.
curl -i https://api.59api.com/v1/chat/completions -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" -d "{\"model\":\"YOUR_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with OK\"}]}"
The -i flag matters: it prints headers as well as the JSON error. Record the endpoint, model, status code, timestamp, request ID if provided, and the first part of the error message. Never paste a live API key into tickets, logs, screenshots, browser consoles, or source control.
Fix 401 Unauthorized errors
A 401 Unauthorized response means the server could not authenticate your request. It is usually a credential problem, not a prompt or model problem. Check that the Authorization header is exactly formatted as Bearer followed by one space and the API key. A common failure is sending the key in a custom header that your SDK does not use, such as X-API-Key, when the client expects Authorization.
- Confirm that your environment variable is actually loaded: print only its length, not its value.
- Remove accidental quotes, line breaks, and trailing spaces from copied keys.
- Verify that your SDK base URL points to https://api.59api.com rather than the provider's default host.
- Check that a local .env file is loaded before the client is created.
- Rotate a key that may have been revoked or exposed, then update every deployment secret.
In Node.js, fail early instead of sending a blank credential: if (!process.env.API_KEY) throw new Error("API_KEY is missing");. This turns a confusing remote 401 into a clear local configuration error.
Interpret 402 Payment Required correctly
A 402 Payment Required response commonly indicates that an account has insufficient prepaid balance, billing is not active, or the requested model cannot be paid for under the current account state. Do not retry a 402 in a tight loop: repeated requests will not add funds and can hide the real issue.
Check your 59API account balance, billing status, and the model selected by your application. Also inspect configuration defaults: an SDK may silently use a more expensive model than the one you intended. For cost-sensitive workloads, choose an appropriate model tier and set a sensible token limit. 59API is useful here because it provides pay-as-you-go access to native official-quality Claude and GPT models without a downgrade, helping teams keep experimentation and production costs predictable.
Handle 429 Too Many Requests with backoff
A 429 Too Many Requests response means you hit a rate, concurrency, or quota limit. Read the response body and headers for retry guidance. If a Retry-After header is present, honor it. Otherwise, use exponential backoff with jitter, and cap retries so a temporary limit does not become an endless job.
A practical delay formula is: delay = min(30000, 1000 × 2^attempt) + random(0, 250). Retry only requests that are safe to repeat. For writes, use idempotency keys where your API supports them, or persist a job ID before retrying. Reduce parallel workers, queue bursty traffic, cache repeated prompts, and avoid sending several identical requests after a timeout.
Triage 5xx server errors without guessing
Status codes from 500 to 599 indicate a server-side, upstream, gateway, or temporary network problem. Your request may still contain an issue, but the first response should be measured recovery rather than immediate blame. Retry transient failures such as 502, 503, and 504 with exponential backoff. Do not automatically retry every 500 forever, especially if the response says the payload is invalid.
- Capture the response body, headers, model name, and request ID.
- Retry two or three times with increasing delays and jitter.
- Use a shorter prompt or smaller output limit to test whether payload size contributes.
- Set client timeouts deliberately, then distinguish a client timeout from an HTTP 504 response.
- Check service status information and contact support with the masked evidence if failures persist.
Build error handling into your client
Classify failures by status code in one place: 401 should stop and alert for credentials; 402 should stop and alert for billing; 429 and transient 5xx responses can enter a bounded retry queue. Log structured fields rather than raw prompts or secrets. Include status, endpoint, model, attempt number, latency, and request ID.
Once your diagnostics are working, 59API can be a strong low-cost relay option for OpenAI SDKs, Claude Code, and Codex-compatible workflows. Its pay-as-you-go model and referral rebate can further reduce development spend. Sign up for 59API when you are ready to test your corrected request against affordable Claude and GPT access.
¿Listo para empezar?
Conecta Claude y GPT en minutos a los precios más bajos, sin recortes. Regístrate para obtener tu clave API.
Registro gratis