API SAST
API error handling best practices
Design RFC 7807 compliant errors, avoid information leakage, and keep clients resilient.
Published: February 3, 2026 • Author: APISAST
Published: 3 February 2026 · Updated: 19 September 2026
Why error handling matters
An error response is part of the public API contract. Inconsistent status codes and messages make retries unreliable and can reveal sensitive implementation details. A stable taxonomy helps clients recover and gives operators a useful signal when a dependency or permission check fails.
Adopt RFC 7807 consistently
RFC 7807 introduced a problem-details JSON format; RFC 9457 now supersedes it. The familiar fields include type, title, status, detail, and instance. APISAST checks for documented error responses and several of these fields in the OpenAPI schema, and can flag debug fields such as a stack trace.
{
"type": "https://example.com/problems/unauthorized",
"title": "Authentication required",
"status": 401,
"detail": "Bearer token missing or expired",
"instance": "/orders/123"
}Define reusable components in OpenAPI so every 4xx/5xx response inherits this structure. When paired with the static API security scanner, you can prevent regressions before merge.
Avoid information leakage
- Do not return stack traces, SQL fragments, or upstream service names.
- Log correlation IDs server-side and expose only the correlation token to clients.
- Normalize messages: “Invalid credentials” rather than “User not found.”
APISAST can flag debug fields in documented error schemas. It does not require a correlation token or inspect actual runtime messages, so test live failures and logs as well.
Status code and taxonomy tips
- Use 400 for validation errors, 401 for auth, 403 for authorization, 404 for object lookup, 429 for throttling.
- Document rate limiting headers (Retry-After, X-RateLimit-Remaining) for every throttled endpoint.
- Provide machine-readable error codes that map to remediation advice in docs.
Check the API security scanner page for how static checks map these behaviors to OWASP categories.
Add examples for client resilience
Include examples for common failures (expired token, validation error, quota exceeded). Clients can test against these fixtures and avoid brittle assumptions.
Reuse response components and examples in OpenAPI so clients see the same shapes across operations. APISAST checks documented error structures; integration tests must verify the service actually returns them.
Design errors around client decisions
A useful error tells the client whether to correct a request, obtain a new token, ask for permission, wait, or contact support. Map these decisions to stable HTTP status codes and a small set of documented problem types. For example, a malformed filter is a 400, an absent token is a 401, a forbidden resource is a 403, and an exhausted quota is a 429. Avoid turning every failure into a 200 response with an error flag; generic HTTP clients then cannot distinguish success from failure.
Keep human-readable detail concise and safe. Give support teams a request ID in logs, and optionally expose that ID to the client without including stack traces or SQL fragments. For authentication failures, wording should not disclose whether a particular account exists. The problem-details implementation guide shows how to express the format in a response schema.
Make retries predictable
A client can retry a transient 503 after a delay, but should not repeat an invalid 400 unchanged. For a 429, return a Retry-After header when the server can predict the next safe attempt. Document whether write operations support idempotency keys before recommending automatic retries. Otherwise a timeout after a successful write can cause a duplicate order or payment when the client resends the same request.
Test the behaviour with a real client library, not only a static schema. Verify that it stops after a bounded number of retries, uses backoff with jitter, and surfaces a useful message to the user. Monitor retry rates separately from underlying failures: aggressive retries can turn a small outage into a larger one.
Review failure paths before release
Create a table of expected failures for each important operation: validation, unauthenticated access, insufficient permission, missing resource, quota exhaustion, and dependency failure. Put the common responses in OpenAPI, then compare examples with integration-test results. Look at the actual body and headers, because a schema can be correct while an exception handler still returns HTML or a debug traceback.
Treat new error types as contract changes. Tell SDK owners whether an existing response code gained a new problem type and whether the client should change its recovery path. Scan the updated specification with APISAST to find missing or inconsistent declarations, then exercise a representative failure from each category in staging. This separates design review from runtime evidence.
Where to go next
Run a scan on your spec to see which endpoints lack structured errors. Then read the OpenAPI security scanner guide or the broader API security SAST tools article for rollout plans.
Scan my spec