Few engineering problems waste more cross-team time than vague API errors. A backend returns 400 with { "error": "failed" }, a browser drops a POST request due to a failing OPTIONS preflight that works fine in curl, or a payment webhook fails signature validation because middleware silently reformatted whitespace.
Fixing these issues fast requires reading the HTTP wire contract accurately rather than guessing from client console noise. This guide covers the status codes teams confuse most, how browser CORS enforcement actually works, how to verify webhooks deterministically, and how to validate OpenAPI contracts before shipping.
HTTP Status Codes That Actually Communicate What Broke
Returning generic 200 OK wrappers around error payloads—or throwing 500 Internal Server Error for missing user fields—breaks automated retries, monitoring dashboards, and API client generators. Use an HTTP Status Code Lookup to keep these critical pairs distinct:
401 Unauthorized vs. 403 Forbidden
401 Unauthorized(Unauthenticated): The server does not know who the caller is—missingAuthorizationheader, expired session cookie, or invalid signature. Standards-compliant401responses include aWWW-Authenticatechallenge header so clients know whether to sendBearertokens or re-authenticate. (Review our JWT authentication audit guide for safe401error messages that avoid leaking signature oracle hints.)403 Forbidden(Authenticated, Not Permitted): The caller proved their identity cleanly, but their role, tenant ID, or IP policy lacks access to that specific resource. Retrying with the exact same credentials will never succeed.
400 Bad Request vs. 422 Unprocessable Content
400 Bad Request: The client sent syntactically broken HTTP or malformed serialization—corrupted JSON syntax, invalid UTF-8 bytes, or unreadable multipart boundaries.422 Unprocessable Content: The JSON parsed cleanly, but the payload violates business or schema rules (missingemail, negative quantity, or invalid enum state). Separating syntax errors (400) from field-level validation (422) immediately tells integration partners where their bug lives.
429 Too Many Requests + Retry-After
Rate-limited clients do not know how long to pause unless you explicitly tell them. Pair 429 with Retry-After: 30 (seconds) or an HTTP timestamp, and expose quota state cleanly—otherwise aggressive client retry loops can turn a mild traffic spike into a self-inflicted outage.
502 Bad Gateway vs. 503 Service Unavailable vs. 504 Gateway Timeout
When an API behind NGINX, Cloudflare, or an AWS ALB fails, the proxy status code narrows the blast radius immediately:
502 Bad Gateway: Your reverse proxy connected to the upstream application server, and the upstream closed the socket mid-response or returned invalid HTTP (classic crash/OOM symptom).503 Service Unavailable: The upstream pool has zero healthy instances, is mid-restart, or intentionally shed load during maintenance.504 Gateway Timeout: The TCP handshake succeeded, your app started work (often a slow unindexed database query or external API call), and the proxy gave up waiting for headers before its read timeout expired.
Why CORS Works in curl and Postman—Then Fails in the Browser
"The endpoint works in Postman, why is Chrome blocking it?" Every web engineer hears this weekly. The reason is straightforward: CORS (Cross-Origin Resource Sharing) is a browser enforcement policy, not a server firewall. curl, mobile native apps, and backend jobs do not enforce CORS at all.
A browser considers two URLs different origins whenever scheme, hostname, or port differs (https://app.example.com calling https://api.example.com, or http://localhost:5173 calling http://localhost:8000).
Simple Requests vs. Preflighted OPTIONS Requests
Simple GET or POST calls with Content-Type: application/x-www-form-urlencoded or text/plain skip preflight. Almost every modern JSON API request triggers an automatic OPTIONS preflight first because it uses one or more of:
Content-Type: application/json- Custom headers like
Authorization: Bearer ...,X-API-Key, orX-CSRF-Token - HTTP methods beyond
GET/HEAD/POST(PUT,PATCH,DELETE)
If the OPTIONS response fails auth middleware with 401 or 403, or omits the matching headers generated cleanly by a CORS Header Generator, the browser aborts the real request before a single byte of JSON leaves the tab.
The Three Classic Production CORS Mistakes
- Wildcard origin + credentials crash: Returning
Access-Control-Allow-Origin: *together withAccess-Control-Allow-Credentials: trueviolates the Fetch specification; browsers reject it instantly. When cookies or credentials are enabled, the server must validate the incomingOriginagainst an explicit allowlist and echo back that exact origin string. - Forgetting
Vary: Originbehind a CDN: If your origin dynamically echoesOrigin: https://app.example.comwithoutVary: Origin, a CDN may cache that response and serve it tohttps://staging.example.comorhttps://docs.example.com, breaking staging unexpectedly. - Unreadable pagination or rate-limit headers in JavaScript: Even when a
200request succeeds,fetch()JavaScript hides custom headers likeX-Request-Id,X-RateLimit-Remaining, orETagunless explicitly whitelisted inAccess-Control-Expose-Headers.
To inspect live wire headers from any endpoint, compare raw header responses with an HTTP Headers Checker or HTTP Header Analyzer, and generate reproducible shell snippets with a cURL Generator or HTTP Request Builder. (Note: because browser-based testers operate under browser Origin rules, APIs whose servers forbid third-party browser reads must still be tested directly from terminal curl when diagnosing non-CORS endpoints.) Also pair CORS hygiene with proper hardening from our HTTP security headers guide.
Deterministic Webhook Signing With HMAC-SHA256
Relying solely on IP allowlists to trust incoming billing or Git webhooks breaks whenever cloud providers rotate egress ranges. Cryptographic HMAC-SHA256 signatures solve this cleanly—provided both sides hash the exact same byte stream.
Most webhook verification bugs trace back to one of two mistakes:
- Re-serializing parsed JSON instead of hashing the raw request body: Frameworks that decode incoming JSON into an object and run
JSON.stringify(req.body)before computing the HMAC alter key ordering, floating-point notation, or whitespace—making valid signatures fail unpredictably. Always capture raw request bytes before JSON parsing middleware runs. - Skipping timestamp replay protection and constant-time equality: Sign
timestamp + "." + rawBody(X-Signature-Timestamp), reject timestamps older than ~300 seconds so captured payloads cannot be replayed indefinitely, and always compare digests using timing-safe functions (hash_equalsin PHP,crypto.timingSafeEqualin Node.js,hmac.compare_digestin Python).
You can generate and verify sample payload digests locally without exposing secret keys via an HMAC Signature Generator.
Keeping OpenAPI Contracts Honest Before Production
Broken API documentation erodes developer trust faster than missing features. Before merging endpoint changes or handing a specification to mobile/frontend teams, audit the schema itself:
- Validate structural completeness early: Run specs through an OpenAPI Validator and preview rendered endpoints with an OpenAPI Viewer to catch missing
openapi/swaggerversion headers, missinginfoorpaths, broken internal$reftargets, or missing error response schemas (400,401,422,429). - Keep YAML vs. JSON conversions clean: Many teams author specs in YAML and publish JSON bundles to SDK generators. Watch out for YAML 1.1 traps like unquoted
no/yesbecoming booleans or indented multiline descriptions breaking structure. Test round-trips carefully with YAML to JSON and JSON to YAML, and double-check nested payload schemas against our JSON Schema and production data guide. - Avoid version-mismatch assumptions (
3.0vs.3.1): OpenAPI3.0usesnullable: true, whereas OpenAPI3.1aligns with modern JSON Schema using type arrays like["string", "null"]. Picking one version deliberately prevents code-generator failures across TypeScript, Go, and PHP clients.
Bottom line: Treat HTTP status codes, CORS response headers, raw-byte HMAC verification, and OpenAPI schema checks as first-class code paths. Clear contracts turn hour-long "works on my machine" API mysteries into thirty-second fixes.