Debug API Failures: 401, 402, 429 and 5xx
Debugging Failed API Requests: 401, 402, 429 and 5xx
Failed API requests are frustrating because the same code can work one minute and fail the next. The fastest way to fix them is to stop guessing and debug in layers: request configuration, authentication, billing, rate limits, server reliability, then client retry logic. This tutorial walks through a practical workflow for AI API calls, using 59API as the example relay because it supports Claude Opus, Sonnet, Haiku, Fable and GPT models through a low-cost, pay-as-you-go endpoint compatible with Claude Code, Codex and OpenAI SDK-style integrations.
Step 1: Capture the Complete Request and Response
Before changing code, record the facts. For every failed request, capture the HTTP status code, response body, request URL, headers, model name, timestamp, request ID if present, and whether the failure is reproducible. Be careful not to log full API keys in production logs.
For 59API, confirm that your base URL is exactly https://api.59api.com. A surprising number of failures come from pointing one environment at the wrong host, using a stale proxy URL, or mixing test and production keys.
- URL: Verify the base URL and endpoint path.
- Headers: Confirm Authorization and Content-Type are present.
- Payload: Check model name, messages, max tokens and JSON formatting.
- Response body: Read the error message, not just the status code.
Step 2: Fix 401 Unauthorized Errors
A 401 means the server could not authenticate your request. Start with the Authorization header. Most OpenAI-compatible SDKs send a bearer token, so your header should effectively be Authorization: Bearer YOUR_API_KEY. If you are using environment variables, print only the first and last few characters to confirm the right key is loaded without exposing it.
Common 401 causes include an empty environment variable, copying a key with extra spaces, using a revoked key, sending the key to the wrong base URL, or deploying without secrets configured. In CI/CD, check whether the secret name matches your code. Locally, restart your terminal or application after editing environment variables.
- Regenerate the key if you suspect it was leaked or revoked.
- Check that staging, production and local environments use the intended key.
- Confirm your SDK is not overriding headers with another client configuration.
Step 3: Resolve 402 Payment Required
A 402 usually means the account cannot pay for the requested usage. With AI APIs, this often points to insufficient balance, expired billing method, spending cap, or an account-level restriction. The fix is not in your JSON payload; it is usually in the account dashboard.
If you use 59API, this is where its pay-as-you-go pricing is helpful: you can add only the balance you need, keep costs predictable, and still access native official-quality Claude and GPT models without model downgrade. If you are building tools, agents or coding assistants, that cost control matters because failed billing checks can interrupt background jobs and user sessions.
- Check current balance and recent usage.
- Look for monthly caps, project caps or organization-level limits.
- Retry only after billing is restored; repeated retries will not solve 402.
Step 4: Handle 429 Rate Limit Errors Correctly
A 429 means you are sending requests faster than allowed. Do not fix it by immediately retrying in a tight loop. That makes the problem worse. Instead, inspect the response for retry guidance, reduce concurrency, and implement exponential backoff with jitter.
A good pattern is to retry after a short delay, then double the delay on each attempt, adding random jitter so many workers do not retry at the same time. Also separate rate limits from token limits: a small request and a huge context-window request may affect limits differently.
- Limit concurrent requests per user, worker or queue.
- Batch non-urgent jobs instead of firing all at once.
- Use smaller prompts and cap max tokens where possible.
- Cache repeated responses for deterministic internal tasks.
- Retry 429 only after a delay, not instantly.
Step 5: Diagnose 5xx Server Errors
5xx errors indicate the server or upstream provider failed to complete the request. Your code may be correct, but you still need defensive handling. First, determine whether every model fails or only one model. Then test a minimal request with a short prompt. If the minimal request succeeds, your original request may be too large, too slow, or hitting an edge case.
For AI applications, 500, 502, 503 and 504 should generally be treated as retryable. Use capped retries, such as three attempts with exponential backoff. If your task is not safe to repeat, attach an idempotency key or store job state so you do not duplicate user-visible actions.
- 500: Unexpected server error; retry with backoff.
- 502: Gateway or upstream issue; often temporary.
- 503: Service overloaded or unavailable; retry later.
- 504: Timeout; reduce prompt size or increase client timeout if appropriate.
Step 6: Test With a Minimal Known-Good Request
When debugging, remove variables. Send the smallest possible chat completion using a known model, one simple user message, and a modest token limit. If that works, add your original settings back one by one: system prompt, tools, longer context, streaming, temperature, and application metadata.
This method quickly reveals whether the failure is caused by authentication, account status, model naming, payload size, streaming code, or tool schema validation. It is especially useful when migrating between providers because SDK-compatible does not always mean every custom option is accepted by every route.
Step 7: Add Production-Grade Error Handling
Your final fix should not be a one-time patch. Build an error handling layer that classifies responses. Treat 401 and 402 as non-retryable until configuration or billing changes. Treat 429 and most 5xx responses as retryable with limits. Store request IDs and timestamps so support can investigate faster.
59API is a strong choice if you want low-cost access to Claude and GPT models through a familiar OpenAI-compatible workflow, while keeping flexibility for Claude Code, Codex and other developer tools. If you are optimizing both reliability and spend, consider signing up and testing your existing SDK configuration against https://api.59api.com.
- Alert immediately on repeated 401 or 402 errors.
- Throttle and queue work on 429 errors.
- Retry 5xx errors with capped exponential backoff.
- Log sanitized request details for every failed call.
- Create a dashboard for error rate by model, endpoint and customer.
Once you follow this workflow, failed API requests become diagnosable events instead of mysteries. Read the status code, verify the layer it points to, apply the correct fix, and make your client resilient before the next traffic spike.