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
Why error handling matters
Poorly designed errors leak implementation details, confuse clients, and slow incident response. The OWASP API Security Top 10 flags verbose errors and inconsistent status codes as a common weakness. Standardizing responses makes debugging faster and keeps security teams confident that sensitive data never escapes.
Adopt RFC 7807 consistently
RFC 7807 defines a simple problem-details JSON format with fields type, title, status, detail, and instance. APISAST checks for these fields and flags responses that fall back to ad hoc payloads or include stack traces.
{
"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 flags responses that include debug fields or omit correlation tokens. Combine with runtime observability to trace issues without revealing internals.
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.
Use components/examples in OpenAPI so every endpoint inherits the same payloads, and let APISAST verify presence and structure.
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