Choosing Accurate HTTP Status Codes for REST APIs and Reverse Proxies
Consistent HTTP status semantics save hours of client debugging. Keep three high-frequency pairs distinct: 401 Unauthorized actually means unauthenticated (missing/expired credentials, paired with WWW-Authenticate), whereas 403 Forbidden means authenticated but lacking permission; 301/302 historically allow browsers to rewrite POST to GET on redirect, whereas 308/307 strictly preserve the original HTTP method and body; and 400 signals malformed syntax while 422 signals valid JSON that failed business/schema validation.
On the server side (5xx), distinguishing 502 Bad Gateway (upstream returned an invalid/truncated response), 503 Service Unavailable (overloaded or intentional maintenance, ideally with Retry-After), and 504 Gateway Timeout (upstream did not respond before proxy_read_timeout) points on-call engineers directly at the failing layer.
- RFC AuthorityAligned with IETF RFC 9110 (HTTP Semantics), RFC 6585 (428/429/431), and RFC 9111 (HTTP Caching).
- Heuristically CacheablePer RFC 9110, 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501 are cacheable by default unless Cache-Control overrides.
- Mandatory Paired HeadersHighlights 401 → WWW-Authenticate, 405 → Allow, 3xx → Location, and 429/503 → Retry-After.
When should a REST API return 400 vs 422?
Return 400 Bad Request for malformed JSON syntax, invalid UTF-8, or unreadable query parameters. Return 422 Unprocessable Content when the JSON parses cleanly but fails semantic validation (e.g., end_date before start_date).
What is the difference between 301 and 308 redirects?
Both are permanent redirects (cacheable by browsers and search engines), but 308 strictly forbids changing a POST/PUT request into GET—making 308 safer for API endpoints.
Should an HTTP 204 No Content response ever include a JSON body?
No. RFC 9110 forbids a message body on 204 responses; proxies and HTTP clients will discard it or hang waiting for Content-Length bytes.