10 Most Common API Error Codes (and How to Fix Them in 2026)
When your first API call fails, the response body is often less useful than the status code. Documentation typically focuses on success paths; the error paths are where you spend the actual debugging time. This guide walks through the ten HTTP error codes you will see most often when building or integrating against an API, what each means, and how to fix it.
For the complete status code reference across all five families, see our HTTP status codes guide. For the question of which code to return for each CRUD action when you are designing the API, see which status code for CRUD.
Understanding HTTP status codes
HTTP status codes are three-digit numbers returned with every response. They tell the client what happened before any parsing of the response body. The codes are divided into five families: informational (100-199), success (200-299), redirection (300-399), client errors (400-499), and server errors (500-599). Codes from 400 to 599 indicate that the request did not produce the expected result.
The number is for programmatic recognition; the reason phrase (OK, Not Found, Internal Server Error) is for humans. Both follow the same rule, even for custom codes.
Error types and causes
HTTP errors fall into two broad classes:
- Client-side errors (4xx) happen when the request itself is wrong: malformed syntax, missing or invalid auth, insufficient permissions, exceeded rate limits, or addressing a resource that does not exist. The client needs to change something before retrying.
- Server-side errors (5xx) happen when the server fails to process a valid request. Overload, internal exceptions, unreachable upstream services, or maintenance downtime. The client did nothing wrong; only the server can fix it.
Distinguishing the two is the first step in debugging. A 4xx tells you to inspect your request; a 5xx tells you to retry with backoff and, if it persists, contact the API provider.
Client-side status codes
Status codes in the 4xx range typically indicate client-side errors, though changes to the API can also trigger them. Here are the five most common, and how to resolve each.
400 Bad Request
The 400 Bad Request error indicates that your API request was not properly formatted. The server could not parse what you sent.
If the response body does not include error details, consult the API’s documentation. The cause is usually one of: a missing query parameter, a missing required field in the request body, an invalid header field, or incorrect syntax in the JSON itself.
A related code that is sometimes returned instead: 422 Unprocessable Entity. The difference is that 400 means the request body could not be parsed (invalid JSON, missing required field at parse-time); 422 means the body parsed cleanly but failed business validation (the email is not in your allowed domain, the price is negative).
401 Unauthorized
The 401 Unauthorized status indicates that the API could not authenticate the request. Either no credentials were sent, or the credentials are invalid or expired.
To fix: confirm you are sending an Authorization header in the format the API documents (Bearer <token> is the most common, but Stripe historically used HTTP Basic auth with the API key as the username (and most SDKs now use Bearer) and AWS uses signed requests). If the credentials look correct, the token may have expired and need to be refreshed. 401 means the request could succeed with valid credentials, which differentiates it from 403.
403 Forbidden
The 403 Forbidden status indicates that you authenticated successfully but the credentials you sent do not have permission to access the requested resource.
This is different from 401: re-authenticating with the same identity will not help, because the identity itself is not authorized. Common causes include using an API key with insufficient scope, attempting to access a resource owned by another customer, or trying to use a feature your subscription plan does not include.
To fix: review the API’s permission model and confirm the credentials you are using have the necessary scope. For subscription-based APIs, check whether the endpoint requires a higher tier.
404 Not Found
The 404 Not Found error signifies that the URL specified in your request does not exist on the API server. This is one of the most common HTTP errors and can have several causes:
- A typo in the URL path
- A change to the API’s URL structure after a version update (look for redirects via
301,308, orSunsetheaders) - A resource ID that does not exist (calling
/users/9999when user 9999 was never created or was deleted) - An API path that exists on a different base URL (staging vs production)
Some APIs also return 404 in place of 403 when they do not want to leak the existence of a protected resource to an unauthorized caller. If you suspect this, check your authentication first before assuming the resource truly does not exist.
429 Too Many Requests
The 429 Too Many Requests status indicates that your client has exceeded the API’s rate limit. The response should include a Retry-After header telling you how long to wait before sending another request.
To fix: implement client-side throttling that respects the rate limit headers (X-RateLimit-Remaining, X-RateLimit-Reset). For long-running clients, exponential backoff with jitter is the standard pattern. If you hit 429 consistently, you may need a higher subscription tier or a more efficient access pattern (fewer calls with larger payloads, caching, batching).
A related code worth knowing: 412 Precondition Failed, returned when conditional headers (If-Match, If-None-Match) do not match the current resource state. Often paired with retries against rate-limited or versioned resources.
Server-side status codes
The 5xx range indicates server-side errors. Sometimes an invalid client request that should have produced a 4xx ends up returning a 5xx because the server did not validate the input before processing. Five most common, with fixes:
500 Internal Server Error
500 can mean anything; the server encountered an unexpected exception. The cause might be related to your request (an edge case the server did not handle) or completely unrelated (a backend bug, a database hiccup).
To fix: double-check that your request matches the documented format (query fields, body fields, headers). If your request is well-formed and the issue persists, contact the API’s support team. Quote any X-Request-Id or trace ID in the response, since that is how the API’s team will find your specific call in their logs.
501 Not Implemented
The 501 Not Implemented status indicates that the HTTP method you used is not supported for any resource on the API. Distinct from 405 (Method Not Allowed), which means the specific URL does not accept that method.
To fix: try a different HTTP method. If you are calling a PATCH and getting 501, the API might only support PUT for updates. The API’s documentation should specify which methods are valid.
502 Bad Gateway
The 502 Bad Gateway response indicates that the server you reached is a proxy or load balancer, and the upstream API server did not respond with a valid HTTP response. The proxy reached the upstream service but received something it could not relay.
Causes: the upstream API server crashed, the network between the proxy and the API server failed, or the upstream service is in the middle of a deployment. 502 is generally a transient problem on the API provider’s side. Retry with backoff; if it persists for more than a few minutes, contact the provider.
503 Service Unavailable
The 503 Service Unavailable status signifies that the server is temporarily unable to handle the request, usually because it is overloaded or undergoing maintenance. The response should include a Retry-After header telling you when to try again.
To fix: implement a delay before retrying. If the error persists for an extended period, reach out to the API provider. 503 is what a well-behaved API returns during planned maintenance or capacity events; if you see it consistently outside of maintenance windows, the provider may be under-resourced.
504 Gateway Timeout
The 504 Gateway Timeout response is similar to 502, except the upstream API server did not respond in time rather than responding incorrectly. The proxy waited, hit its timeout, and returned 504 to the client.
Causes: high network latency between the proxy and the upstream API, the API server taking too long to process the request (long-running queries, slow upstream dependencies), or a deliberate timeout on the proxy that does not match the upstream’s actual response time. 504 can also occur when you request an excessive amount of data, so trimming the request size is a useful diagnostic.
To fix: if your request is large or computationally heavy, consider breaking it into smaller requests. If it is reasonable and the 504 persists, contact the provider.
Best practices for error handling
Error handling is one of the parts of API design that compounds the most over time. Three patterns that hold up across APIs:
- Use meaningful error messages. Pair every error code with a machine-readable identifier (e.g.,
payment_method_declined) and a human-readable message. Avoid generic “An error occurred” responses; consumers cannot debug against them. - Log errors centrally. Track and analyze error patterns. A spike in a particular error code across customers indicates a systemic issue worth addressing; a spike on a specific customer’s traffic indicates a customer-support issue. Both need visibility.
- Use standardized HTTP codes. Custom codes outside the 100-599 range break HTTP clients, proxies, and frameworks. Stay within standard codes and put detail in the response body.
- Centralize error handling on the server side. A single middleware layer that maps internal exceptions to HTTP status codes plus consistent JSON error envelopes is much easier to maintain than per-endpoint error code.
- Test error paths. Simulate the conditions that produce each error code. The error paths are where most production support tickets come from, so they deserve the same test coverage as success paths.
Error handling for AI agent retries
This is the 2026 update worth knowing about even if everything above stays the same.
AI agents call APIs as part of multi-step tasks, and they retry aggressively on transient failures. Two behaviors matter for your error handling:
429 Too Many Requestsis the agent-safe signal for rate limiting. Agents respect429with aRetry-Afterheader and slow down their retry cadence accordingly. Returning503for rate-limited traffic confuses the agent into treating the situation as a server outage and retrying aggressively, which makes the overload worse. Reserve503for genuine outages and429for capacity management.- Idempotency keys reduce duplicate writes. When an agent retries a
POST(because the network blipped, or because the agent runtime is conservative), without idempotency you get duplicate orders, duplicate charges, and duplicate emails. Accept anIdempotency-Keyheader on everyPOSTandPATCH, cache the response keyed on it, and return the same response on retry. The convention was popularized by Stripe’s API and is now widely used across payments, fintech, and infrastructure APIs.
These two patterns are now table stakes for any API that expects agent traffic, which in 2026 is most of them.
How Moesif monitors API errors in production
A list of error codes is only useful if you can see which ones are actually occurring on your live API. Moesif records the status code distribution per endpoint and per customer in real time, with alerting when error rates spike on a specific endpoint or for a specific customer.
The kinds of questions Moesif’s error monitoring answers in seconds rather than hours:
- Which customer is getting the most 4xx errors today? (Likely an integration that needs support.)
- Which endpoint has the highest 5xx rate this week? (Likely a server-side problem to investigate.)
- Did the 429 rate spike after the latest deploy? (Likely a regression in rate-limit configuration.)
- Are agent-driven retries hitting
503instead of429? (Likely a misconfiguration that is amplifying load.)
Pair the monitoring with the design-time guidance covered above (status code semantics + CRUD-action mapping) and the loop closes: pick the right code at design time, return the right code at runtime, observe the actual code distribution in production.
Summary
You will see many error codes when building or integrating against APIs, and most have reasonable fixes. Some are related to server errors and some to client-side errors; sometimes one causes the other. Read the API’s documentation carefully, log errors centrally for analysis, and reach out to the provider when issues persist.
If you want to see your live API’s error distribution per endpoint, per customer, in real time, start a 14-day Moesif free trial. No credit card required.
Frequently asked questions
What does an API error code mean? It is the HTTP status code returned with an unsuccessful API response. Codes from 400 to 499 mean the client’s request was wrong; codes from 500 to 599 mean the server failed to process the request.
What is the difference between a 400 and a 422 error? 400 Bad Request means the request body could not be parsed (invalid JSON or missing required field). 422 Unprocessable Entity means the body parsed cleanly but failed business validation. Use 400 for syntax errors and 422 for semantic ones.
Why am I getting a 401 error? Your credentials are missing, invalid, or expired. Confirm you are sending the Authorization header in the format the API documents, and that your token has not expired.
Why am I getting a 429 error? You are exceeding the API’s rate limit. Check the Retry-After header in the response, wait that long, then retry. Implement client-side throttling that respects X-RateLimit-Remaining to avoid the limit altogether.
What is the difference between a 502 and a 504? Both indicate that an upstream API server failed to deliver a valid response to a proxy. 502 means the upstream returned something invalid; 504 means the upstream did not respond in time. Both are transient on the provider side and typically resolve with backoff.
Should I retry on 5xx errors? Yes, with exponential backoff and a maximum retry count. 5xx errors are typically transient. Do not retry on 4xx errors unless you have changed the request, because the same request will produce the same error.