Debug 401, 402, 429 and 5xx API Errors
Debugging Failed API Requests: 401, 402, 429 and 5xx
When an API request fails, the status code is your first clue. For developers using AI models through OpenAI-compatible SDKs, Claude Code, Codex or direct HTTP calls, most failures fall into a few common groups: authentication problems, billing problems, rate limits and server-side errors. This guide explains how to debug 401, 402, 429 and 5xx responses step by step, using practical checks you can apply immediately.
If you use 59API as your AI API relay, the same debugging principles apply. 59API provides cheap, pay-as-you-go access to Claude models such as Opus, Sonnet, Haiku and Fable, plus GPT models, through a base URL of https://api.59api.com. Because it is compatible with the OpenAI SDK and popular coding tools, you can usually fix failed requests without rewriting your app.
Start With the Full Error Response
Do not debug from the status code alone. Capture the full response body, request URL, headers, model name, timestamp and request ID if one is returned. Many APIs include a message that explains whether the key is invalid, the account lacks balance, the model name is wrong or the request exceeded a limit.
Also confirm which base URL your code is calling. A surprisingly common mistake is sending a valid key to the wrong endpoint. For 59API, your SDK or HTTP client should point to https://api.59api.com. If you are using an OpenAI SDK, check the baseURL or equivalent configuration in your language.
401 Unauthorized: Check Authentication First
A 401 error means the API could not authenticate your request. This is usually not a model problem. It is almost always a key, header or configuration issue.
- Verify the API key: Make sure you copied the complete key with no missing characters, spaces or line breaks.
- Use the correct header: Most OpenAI-compatible APIs expect an Authorization header using Bearer followed by your API key.
- Check environment variables: If your app reads the key from OPENAI_API_KEY or another variable, print a safe partial value during local debugging, such as the first and last few characters.
- Restart your process: Servers, terminals and containers often need a restart before updated environment variables take effect.
- Confirm account access: If the key was revoked, regenerated or belongs to another workspace, create a fresh key and update your deployment secrets.
For Claude Code, Codex or an OpenAI SDK integration, double-check both the API key and base URL together. A valid 59API key should be paired with https://api.59api.com, not a default provider endpoint, unless you intentionally configured otherwise.
402 Payment Required: Billing or Balance Issue
A 402 error usually means your request is technically valid, but the account cannot pay for it. This can happen when your balance is too low, billing is not enabled or a spending control blocks the request.
- Check your balance: Log in to your provider dashboard and confirm available credit.
- Review spending limits: Daily, monthly or project-level caps can stop requests even when the account has funds.
- Look at model cost: Larger models cost more per token. A request that works on a smaller model may fail if your remaining balance is low.
- Reduce token usage: Lower max output tokens, shorten prompts and avoid sending large conversation histories unnecessarily.
This is where a low-cost relay can make development easier. 59API is designed for cheap, pay-as-you-go access to official-quality native models without downgrading the model behind the scenes. For teams testing agents, coding assistants or high-volume chat features, lower per-request cost reduces the chance that debugging sessions quickly consume the budget. 59API also offers a referral rebate, which can further reduce ongoing usage costs.
429 Too Many Requests: Slow Down and Retry
A 429 error means you are sending too many requests, too many tokens or too much concurrency for the current limit. Beginners often assume this is a permanent failure, but it is usually recoverable with better request pacing.
- Add exponential backoff: Retry after a short delay, then increase the delay after each failed attempt.
- Respect retry headers: If the response includes a retry-after value, wait at least that long before trying again.
- Limit concurrency: Use a queue so your app does not fire hundreds of requests at once.
- Batch carefully: Combine small tasks when appropriate, but avoid creating huge prompts that exceed token limits.
- Cache repeated work: Do not ask the model the same question repeatedly if the answer can be stored.
For AI coding tools and agents, 429 errors may appear during file indexing, test generation or multi-step planning. Reduce parallel tool calls, lower max tokens and add retry logic around model calls rather than around your entire job. This prevents one temporary rate limit from restarting expensive work from the beginning.
5xx Errors: Treat Them as Temporary Unless Proven Otherwise
5xx status codes, such as 500, 502, 503 and 504, indicate the server or upstream service failed to complete the request. You may not be able to fix the root cause, but you can make your app resilient.
- Retry safely: Retry idempotent requests automatically. For actions that create records or charge users, use an idempotency key if supported.
- Use timeouts: Do not let requests hang forever. Set reasonable connect and read timeouts.
- Log request IDs: Request IDs help support teams trace failures quickly.
- Try a smaller request: Very large prompts, long contexts or oversized outputs can make failures more likely.
- Fail gracefully: Show users a helpful message and allow them to retry rather than losing their work.
If a 5xx error persists, compare results across models and request sizes. For example, test a short prompt against the same model, then test the original prompt. If the short prompt succeeds, your payload may be too large or malformed. If all requests fail, check provider status pages or contact support with timestamps and request details.
A Simple Debugging Checklist
- 401: Validate API key, Authorization header, base URL and environment variables.
- 402: Check balance, billing status, spending limits and model cost.
- 429: Add backoff, reduce concurrency, respect retry headers and cache repeated calls.
- 5xx: Retry with limits, log request IDs, reduce payload size and monitor provider status.
Failed API requests are frustrating, but they become manageable when you read the response carefully and map each status code to the right category of fix. If you want low-cost access to Claude and GPT models while keeping compatibility with OpenAI SDKs, Claude Code and Codex, consider signing up for 59API and pointing your client to https://api.59api.com. The cheaper pay-as-you-go pricing makes it easier to test, debug and scale without overpaying for every experiment.
शुरू करने के लिए तैयार?
कुछ ही मिनटों में Claude और GPT जोड़ें, सबसे कम कीमत पर। साइन अप करें और API key पाएं।
मुफ़्त साइन अप