An API error is part of the interface, not an apology after the interface fails. A client needs to know whether it should change the request, ask a user for permission, wait before trying again, or raise an incident. A person needs a message that explains the next useful step without exposing secrets or internal machinery. Those needs overlap, but they are not identical.
Error handling becomes expensive when every endpoint invents its own shape. One returns a string, another returns an array, and a third uses a 200 response with a field named success set to false. Client libraries end up parsing a collection of exceptions, dashboards cannot group failures reliably, and support staff ask customers to paste stack traces. A consistent contract gives both machines and people a stable way to understand what went wrong.
Give HTTP status its proper job
Start with the HTTP response status. It tells generic clients, proxies and observability tools the broad class of outcome: the request was malformed, unauthenticated, not permitted, not found, conflicted with current state, or failed on the server. Use the status semantics consistently. A validation failure should not look like a successful resource fetch merely because the API can encode an error object in JSON.
Status codes alone are not enough for product-specific diagnosis. A 409 could mean that a resource is already in use, that the caller supplied an obsolete version, or that an operation is not allowed in the current state. A 403 may reflect an account policy, a missing role or a feature that is not enabled. The response needs a stable machine-readable detail that narrows the case without replacing the broad HTTP meaning.
Do not use status codes as a secret channel. If an unauthenticated caller should not learn whether a private resource exists, returning different responses for “missing” and “not yours” can leak information. Choose the behavior deliberately, apply it consistently and document it for clients that need to respond. Security requirements sometimes justify less detail than the ideal debugging experience.
Keep transport failures and application problems distinguishable. A gateway can time out before the application produces a response. A proxy may reject the request. A client can fail to parse a valid response because it is using an incompatible model. Include enough request and response context in client diagnostics to distinguish these cases, while avoiding sensitive payloads in routine logs.
Define one envelope with stable fields
For HTTP APIs, the IETF’s RFC 9457 Problem Details format offers a standard envelope for machine-readable error information. Its common members include a problem type, short title, HTTP status, occurrence instance and detail text. It also allows extension members. Teams already using a domain-specific error format do not need to replace it automatically; the point is to give each API a predictable contract rather than a different shape on every route.
Choose a small set of fields and write down their meaning. A response might contain a stable error code, a human-readable summary, an optional field-level validation list and a request identifier. The client should be able to branch on the code or problem type, not on exact English wording. Wording can be clarified, localized or shortened; identifiers should change only when the underlying meaning changes.
Keep the envelope consistent across success and failure boundaries. If one service returns JSON and another returns a problem document with a different content type, client code should still know how to inspect the status and correlation identifier. Set the media type correctly, document content negotiation, and make sure reverse proxies preserve the response body and relevant headers.
A stable envelope is not an excuse to put every internal exception into a public field. The API contract should expose information that helps the caller decide what to do, not reproduce the server’s debug log. Stack traces, SQL statements, filesystem paths, secrets, internal hostnames and unfiltered upstream responses do not belong in ordinary public error responses.
Make codes describe a condition, not an implementation
Use error identifiers that remain meaningful as the server is refactored. `billing.payment_method_required` communicates a domain condition more clearly than `StripeAdapterNullPointer` or `DB-17`. Avoid identifiers tied to source file names, database tables or a third-party library’s exception class. An internal cause can change while the user-visible reason remains the same.
Keep codes specific enough to guide a safe action but not so granular that every code becomes a separate release burden. `invalid_request` is often too broad to resolve a field issue. A code for every malformed character in every field may be too detailed and brittle. A useful scheme can distinguish authentication, authorization, validation, conflict, rate limiting and transient service failure, then provide a stable field path or reason where needed.
Define whether codes are globally unique or scoped to a service, operation or problem type. Document casing, separators and lifecycle expectations. Decide how unknown codes should be handled. A resilient client should be able to show a general message and preserve the code for support, even when it does not yet recognize a newly added value.
Do not require clients to parse the prose. “Your request is invalid because the `start_date` must be earlier than `end_date`” is useful to a person, but a client should not search that sentence for the phrase “earlier than.” Supply a stable code and structured field information for programmatic behavior, then use the text to explain the condition plainly.
Make validation errors actionable
Field-level validation should point to the input that needs attention. Return a stable field path or parameter name, a reason code and a short message. When several fields fail, provide a bounded list so the user can fix them together. Define whether paths use JSON Pointer, schema property names or another convention, and keep that convention consistent.
Be careful with nested or repeated data. An error such as “invalid item” is hard to locate in an array. A path such as `/items/3/quantity` can identify the affected input, but array positions can shift as clients transform data. A client can often match the path to the submitted request, while a human-facing UI should map it back to a visible row and field label.
Do not return the rejected value by default. It may contain a password, token, health detail, personal identifier or an unexpectedly large payload. If echoing a safe value helps correction, limit it to low-risk fields and define redaction. The same care applies to query strings, which can appear in browser history, proxy logs and support screenshots.
Explain which validation rules are stable and which are product policy. A request can be syntactically valid but disallowed by an account limit or current workflow state. Clients may need to distinguish a malformed date from a valid action blocked by a policy. Use different identifiers and messages so the caller can correct input in one case and guide the user or contact an administrator in the other.
Tell clients whether retrying makes sense
Not every error should be retried. A malformed request will not improve when sent again unchanged. An authorization failure needs a permission or credential change. A rate limit may be temporary and should often include a retry hint. A service outage may justify retrying after a delay, provided the operation can be repeated safely.
Define retry behavior by operation and failure condition. A generic `retryable: true` field can be useful only if the API knows the semantics of that request and the information is trustworthy. For an unsafe operation such as creating a charge or sending a notification, the client must know whether the original request could already have taken effect before repeating it. An idempotency key or a status-check operation may be part of that contract.
Use standard HTTP mechanisms where they fit. `Retry-After` can communicate when a client should retry after throttling or temporary unavailability. The server should choose a value that matches its recovery or quota policy; the client should treat it as guidance with reasonable limits, not wait forever on an absurd timestamp. Document whether the value is a delay or an HTTP date if clients need to interpret it.
Do not tell clients to retry every 5xx response without qualification. Some failures are transient, some are configuration errors, and some can occur after a non-idempotent action committed. State which operations support idempotency, how long keys are retained, what happens when a key is reused with a different request, and how a client can reconcile an uncertain outcome.
Backoff and jitter belong in client guidance as well as server policy. A burst of clients retrying immediately can overload an already degraded service. Give realistic limits, include whether the provider may return a `Retry-After` header, and show how SDKs behave. If a client library performs automatic retries, make the eligible methods and status conditions visible.
Separate user guidance from diagnostic detail
The public message should tell the caller what happened at the API boundary. For an end user, that might be “This workspace needs an owner to approve the connection.” For a developer, it may include the missing scope or an invalid field. Neither should receive a raw exception dump. Use server-side logs for implementation diagnostics and connect them to the response through a request or problem-instance identifier.
A request identifier is valuable when it is safe and stable enough to search. Generate it at a trusted boundary, propagate it across relevant internal calls, return it in a response header or documented field, and include it in support instructions. Do not let an untrusted caller choose an identifier that can collide with another request or inject control characters into logs. If you accept a client trace header, validate and bound it.
Problem type URIs can document recurring conditions. RFC 9457 describes the type as the primary identifier of a problem type and encourages documentation where a URI can be resolved. Keep such pages durable and focused: what the condition means, likely causes, safe actions, relevant support channel and any permission requirements. Do not make a problem URL expose incident data or private account information by default.
An occurrence identifier can help support staff find one instance without making the problem type unique for every request. Store enough context server-side to investigate under the organization’s retention and access rules. Avoid placing customer secrets in a URL that might be copied or logged. An opaque, non-guessable identifier is not automatically private; access control still matters if it resolves to sensitive detail.
Protect privacy and security in error paths
Error paths often receive the least attention and the most unusual input. Treat them as part of the attack surface. Bound message length, escape data before rendering it in a developer portal, and avoid returning raw third-party messages without review. Upstream systems can include user-controlled strings or sensitive diagnostic details that were never intended for your customer.
Authentication and authorization failures need useful but careful explanations. Telling a caller which exact account, email address or role exists can help an attacker enumerate targets. At the same time, a legitimate developer needs to know whether a token is expired, a scope is missing or an organization policy denied access. Decide which details are shown to authenticated users, account administrators or support staff, and apply the same policy in the API and the dashboard.
Do not use a success response to avoid showing an error to monitoring. If the operation failed, preserve a status and signal that accurately reflect the outcome. Hiding failures creates confusing client state and makes incident detection harder. If a request was accepted for asynchronous processing, return an explicit accepted state and a resource or operation identifier whose lifecycle the client can query.
Review error bodies for tenant isolation. A validation message or conflict response can accidentally include another customer’s resource name, a query result or an internal identifier. Test errors across permission levels and account boundaries, not only successful responses. A failed request can reveal more than a successful one because the server may include its attempted lookup or internal reasoning.
Support localization without breaking clients
Machine-readable fields should stay stable regardless of the language used for display text. If the API supports localized titles or details, define how the language is chosen and how clients can request it. Do not let a localization change alter the error code, type URI, field path or retry semantics. A client may store a code for a later support request even if the user sees translated wording.
Use short, direct language and avoid blaming the caller. State the condition, then the next useful action. “You failed to provide a valid value” can be improved to “Enter a date after today.” For a permission issue, say who can grant the access or where an administrator can review it. Do not promise that an action will work if only support can confirm it.
Some errors have no user-facing remedy. A service failure can ask the user to try again later, but the API should also offer a diagnostic identifier and publish operational status through its normal channels. Avoid inventing a specific resolution when the cause is unknown. Clear uncertainty is more useful than a confident guess.
Document the catalog and lifecycle
Maintain a catalog of error codes and problem types alongside the API reference. For each entry, record its HTTP status, stable identifier, trigger, safe client action, whether retrying is appropriate, relevant headers, visibility rules and owner. Mark deprecated codes and explain replacement behavior. This catalog can also drive SDK constants, support documentation and monitoring dashboards if generation is reliable.
Version the error contract intentionally. Adding a new optional extension can be safe for tolerant clients but may break strict decoders. Removing a code or changing its meaning can break client logic even when the response schema is unchanged. Treat changes to machine-readable semantics with the same review used for request and response fields.
Keep examples realistic but non-sensitive. Include a success-shaped request context, HTTP status, headers, content type and problem body, and label illustrative identifiers as examples. Do not paste a production incident response that contains real account names or tokens. Make examples consistent across documentation, generated SDKs and automated tests.
Test errors as first-class behavior
For each endpoint, test a valid request and the failures most likely to shape client behavior: malformed input, missing credentials, insufficient permission, missing resource, state conflict, throttling, timeout and an unexpected server failure. Assert the status, content type, stable code, safe message, correlation identifier and retry hints. Include cases where the request partially succeeded or the server cannot know whether an external action completed.
Test clients against unknown error codes and extra fields. A robust client should preserve the response for diagnostics, show a general message when it cannot classify the code, and avoid retrying blindly. Contract tests can ensure that the server does not remove a documented field or change a problem type without an explicit review.
Review operational logs and customer-facing responses separately. Logs may include internal error classes and dependency information under controlled access; responses should expose only the contracted detail. Check redaction in both places. A log entry that stores the raw request may violate the same privacy principle even if the API response is clean.
Ask a developer who did not write the endpoint to integrate with its error behavior using only the published docs. Can they distinguish a bad request from a permission problem? Can they recover from a rate limit without hammering the service? Can they report a failure with a request identifier? If they must inspect source code to answer these questions, the contract is incomplete.
Build toward predictable recovery
Good API errors do not prevent every failure. They make failures classifiable, bounded and recoverable. Status codes provide broad HTTP meaning; stable codes or problem types express domain conditions; messages guide people; headers and request identifiers support safe action and investigation. Each piece should have one job and a documented lifecycle.
Start with a small error catalog for the highest-impact endpoints. Identify which conditions need a customer action, which can be retried, which require administrator help and which need internal investigation. Align server responses, SDK behavior, developer docs and monitoring around that catalog. Then revisit it whenever a new workflow, permission model or asynchronous operation changes what a client needs to know.
When clients can recognize an error without parsing prose, understand whether a retry is safe, and provide a useful identifier to support, the error response becomes part of a dependable integration contract. That is a more durable measure of API quality than the number of exception classes or message variants the server can produce.
Primary references
The IETF RFC 9457 defines Problem Details for HTTP APIs, including problem types, extension members and security considerations. The HTTP Semantics specification, RFC 9110 defines status codes and the `Retry-After` response field. Google Cloud’s API troubleshooting guidance is one example of connecting error details with logs and support. Apply the standards to your own domain contract and threat model rather than copying example codes mechanically.
