How to Handle API Errors (The Right Way)
APIs fail โ networks drop, limits hit, inputs are wrong. Here's how to read errors, retry safely, and build resilient requests.
Every API call can fail — bad input, expired token, rate limit, network blip, provider outage. Robust code treats the failure paths as first-class, not an afterthought.
Always check the status code first
r = requests.get(url, timeout=10)
if r.status_code == 200:
data = r.json()
elif r.status_code == 429:
retry_after = int(r.headers.get('Retry-After', 5))
... # wait and retry
elif 400 <= r.status_code < 500:
... # your bug: log the body, don't retry blindly
else:
... # 5xx: their problem: retry with backoffWhat each class means for you
| 2xx | Success. (Still check the body — some APIs put errors in a 200 payload.) |
| 400 / 422 | Malformed or invalid request. Do not retry unchanged — fix the input. Read the error body for which field. |
| 401 | Authentication failed. Refresh the token or fix the key. Retrying the same request won’t help. |
| 403 | Authenticated but not allowed — plan limit, missing scope, forbidden resource. Not a retry. |
| 404 | Wrong URL or the resource doesn’t exist. Not a retry. |
| 429 | Rate limited. Honour Retry-After; back off. This one is retryable. |
| 5xx | Server-side. Retry with exponential backoff and a cap; then fail gracefully. |
| Network / timeout | No response at all. Retry a bounded number of times; the request may or may not have taken effect. |
Retry the right things, the right way
- Retry: 429, 500, 502, 503, 504, connection errors, timeouts.
- Don’t retry: 400, 401, 403, 404, 422 — the outcome won’t change.
- Use exponential backoff with jitter: wait ~1s, then ~2s, ~4s, ~8s, each ± a random fraction, with a maximum number of attempts.
- For non-idempotent calls (POST that creates something), send an idempotency key if the API supports one, so a retry can’t double-charge or double-create.
- Set an overall deadline — don’t retry forever.
Read the error body
Most APIs return a structured error: a code, a message, sometimes a field or errors[] array. Log it. ‘Request failed with 400’ is useless at 2am; ‘400: start_date must be before end_date’ fixes itself.
Watch for errors hiding in a 200
Some APIs (older SOAP-style ones, and a few JSON ones like Etherscan, Kraken, Aeris) return HTTP 200 with {"status": "error"} or an errors array in the body. Check the documented success flag, not just the HTTP status.
Fail gracefully for your users
- Serve stale cached data with a ‘last updated’ note when the API is down.
- Show a clear, non-technical message and a retry button — not a stack trace.
- Degrade the feature (hide the weather widget) rather than breaking the whole page.
- Alert yourself (logs, error tracker) so you know before customers tell you.
FAQ
Which HTTP errors should I retry?
429 and 5xx (500, 502, 503, 504), plus network timeouts and connection failures — with exponential backoff. Never retry 400, 401, 403, 404 or 422 unchanged.
What is exponential backoff with jitter?
Waiting roughly 1s, 2s, 4s, 8s between retries (doubling), with a small random offset added so many clients don’t retry in lockstep and overload the recovering server.
The response is HTTP 200 but something is wrong — why?
Some APIs report errors inside a 200 body via a status/error field. Always check the API’s documented success indicator, not only the HTTP code.
How do I stop a retry from creating duplicate records?
Use an idempotency key if the API offers one, or design the operation so repeating it is harmless (upsert by a natural key rather than blind insert).
Keep going
Try it on a real API
๐ Explore free public APIs
Hundreds of free APIs, searchable by category, with auth & CORS at a glance.
Browse the directory โ