HTTP Status Codes & REST API Debugging Guide (2xx, 3xx, 4xx, 5xx)

HTTP status codes are the shared vocabulary between web servers, CDNs, browsers, and mobile clients. When an API returns the right status code alongside a structured JSON error body, clients immediately know whether to display a validation message, refresh an expired JWT, back off due to rate limiting, or retry a transient gateway failure. When an API returns 200 OK with {"error": "Not found"} inside the JSON body instead, HTTP caching, monitoring alerts, and automated retry logic break down completely.

In this practical reference guide, we examine the most important status codes in every class (2xx, 3xx, 4xx, and 5xx), clear up classic engineering debates like 401 vs 403 and 400 vs 422, and show how to design standard RFC 9457 Problem Details JSON error responses.

1. Overview of the Five HTTP Status Classes

Every three-digit status code defined in RFC 9110 belongs to one of five categories indicated by its first digit:

RangeCategoryWho Is Responsible?
1xxInformationalProtocol handshakes (e.g. 101 Switching Protocols for WebSockets).
2xxSuccessRequest was received, understood, and accepted cleanly.
3xxRedirectionClient must follow a Location header or reuse cached representation.
4xxClient ErrorCaller sent invalid syntax, missing auth, wrong path, or hit rate limits.
5xxServer ErrorServer, database, or upstream proxy failed while fulfilling a valid request.

2. 2xx Success: 200 vs. 201 vs. 202 vs. 204

Returning 200 OK for every successful endpoint works functionally, yet choosing exact 2xx codes communicates intent clearly to SDKs and browsers:

  • 200 OK: Standard success for GET reads and synchronous PUT/PATCH updates that return the updated JSON representation.
  • 201 Created: Ideal for POST requests that create a brand-new resource. Include a Location: /api/orders/9941 header pointing to the newly created resource URL alongside the JSON object.
  • 202 Accepted: Crucial for asynchronous background jobs (video transcoding, bulk CSV exports, email campaigns). It tells the client "your job is queued and valid, poll /jobs/123 for completion" instead of holding an HTTP connection open until timeout.
  • 204 No Content: Standard for DELETE operations or save actions where no response body is sent. Frontend reminder: Never call response.json() on a 204 response—because the body is empty, JSON.parse("") throws Unexpected end of JSON input (see our JSON Parse Errors Guide).

3. 3xx Redirection & Caching: Why 307 and 308 Matter for APIs

Traditional redirects (301 Moved Permanently and 302 Found) carry an awkward historical browser quirk: clients frequently change a POST request into a GET request and drop the JSON body when following 301 or 302! If you ever move an API endpoint path and want callers to preserve their HTTP method and JSON body:

  • Use 308 Permanent Redirect instead of 301 (method & body preserved, cacheable).
  • Use 307 Temporary Redirect instead of 302 (method & body preserved, temporary).
  • 304 Not Modified: Sent in response to conditional GET requests carrying If-None-Match (ETag) or If-Modified-Since headers. Returning 304 saves huge bandwidth because the client reuses its cached JSON or CSS file without re-downloading the body.

4. 4xx Client Errors: Mastering the Nuances

CodeNameExact Meaning & Common Cause
400Bad RequestMalformed JSON syntax, missing required query parameter, or invalid header.
401UnauthorizedUnauthenticated: Missing, invalid, or expired JWT/API key. Client should authenticate or refresh token.
403ForbiddenUnauthorized: Server knows who you are, yet your role/plan lacks permission for this resource.
404Not FoundResource ID or URL route does not exist (also sometimes used instead of 403 to hide private resource existence).
405Method Not AllowedCalling GET on a POST-only endpoint. Include an Allow header.
409ConflictUnique constraint collision (duplicate email signup) or optimistic concurrency version mismatch.
413Content Too LargeUploaded file or JSON payload exceeds Nginx/API body limit (e.g. client_max_body_size).
415Unsupported Media TypeServer expected Content-Type: application/json, caller sent text/plain or form data.
422Unprocessable ContentValid JSON syntax, yet semantic/business rules failed (e.g. endDate earlier than startDate).
429Too Many RequestsRate limit exceeded. Always inspect the Retry-After response header!

401 vs. 403 Quick Rule: If refreshing your JWT token or logging in could fix the error, return 401. If the user is already logged in as a standard member and tries to hit /admin/users, return 403—re-authenticating as the same user will never grant access.

5. 5xx Server Errors: Debugging 500, 502, 503 & 504

When a production endpoint drops a 5xx error, checking the exact digit reveals which infrastructure layer broke:

  • 500 Internal Server Error: An unhandled exception inside your application code (null pointer, uncaught SQL error, missing environment variable). Check your Node.js/Python/PHP application error logs first.
  • 502 Bad Gateway: The reverse proxy (Nginx, Apache, Cloudflare, AWS ALB) connected to your upstream app server and received a garbage response or abrupt socket close (for example, your Node process crashed mid-request or ran out of memory).
  • 503 Service Unavailable: The server is intentionally overloaded, starting up, or in maintenance mode—often paired with a Retry-After header.
  • 504 Gateway Timeout: Your upstream app server is alive and still crunching a slow database query or third-party API call, yet exceeded the proxy's read timeout (commonly 30s on API Gateway or 60s on Nginx/Cloudflare). Fix by indexing slow SQL queries or moving heavy tasks to async 202 Accepted queues.

Remember also that proxies like Nginx and Cloudflare frequently return HTML error pages for 502 and 504—which is why frontend apps calling response.json() blindly end up crashing with Unexpected token '<'!

6. Designing Clean JSON Errors with RFC 9457 Problem Details

Instead of inventing a custom error format on every project, adopt RFC 9457 (which supersedes RFC 7807) using Content-Type: application/problem+json. It gives every client a predictable error structure:

{
  "type": "https://techcar.online/errors/validation-failed",
  "title": "Your request parameters did not validate.",
  "status": 422,
  "detail": "Two fields in the order payload failed schema constraints.",
  "instance": "/api/v1/orders",
  "traceId": "req_9f2a81bc",
  "errors": [
    { "field": "customerEmail", "reason": "Must be a valid email address" },
    { "field": "items[0].qty", "reason": "Must be an integer >= 1" }
  ]
}

Including a correlation traceId in error responses lets users or frontend logs report one short ID that engineers can immediately look up in backend logs without exposing internal stack traces or database table names to attackers.

7. Safe Retry Rules: Which Codes Should Clients Retry?

Retrying failed requests blindly makes outages worse (a "retry storm") and can double-charge customer credit cards! Follow two strict retry rules:

  1. Never retry 4xx errors (except 429 and 408): Retrying a 400, 401, 403, 404, or 422 with the exact same payload will fail identically every time. For 429 Too Many Requests, wait the duration specified in the Retry-After header before retrying.
  2. Use Exponential Backoff + Jitter on 502, 503, 504: Wait e.g. 1s → 2s → 4s plus a random millisecond jitter so thousands of clients do not hammer a recovering server simultaneously. For non-idempotent POST requests (such as payments), attach an Idempotency-Key UUID header so safe retries never create duplicate charges.

8. Debugging Live Status Codes with cURL & Browser DevTools

When inspecting an API issue from your terminal, cURL's -i (include headers) and -v (verbose TLS/redirect trace) flags let you see status codes, redirects, and raw JSON bodies clearly:

# Print response status + headers + body
curl -i -sS -H "Accept: application/json" https://api.techcar.online/v1/status

# Follow redirects (-L) and print only HTTP status code
curl -sS -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" https://techcar.online/

Whenever a 400 or 422 returns a minified JSON error object, copy the response body into our JSON Formatter & Tree Explorer to inspect nested validation errors cleanly.

9. Status Codes in GraphQL & Webhook Integrations

Two modern API patterns handle HTTP status codes differently than classic REST endpoints, and knowing those rules prevents confusing integration bugs:

  • Webhooks (Stripe, GitHub, Razorpay): Webhook senders treat any 2xx code (200, 202, 204) as successful delivery. Returning 301 or 302 is usually treated as a failure because webhook dispatchers refuse to follow redirects for security. Returning 4xx or 5xx triggers exponential backoff retries over 24–72 hours. Tip: verify signatures quickly, enqueue the payload into Redis/SQS, and return 200 OK in under 2 seconds so slow database work never causes webhook timeouts and duplicate retries.
  • GraphQL Endpoints: GraphQL servers almost always return 200 OK for valid GraphQL execution even when individual resolver fields fail—reporting partial results under "data" alongside an "errors": [...] array. Transport-level failures such as invalid JSON syntax, missing authentication headers, or persisted-query misses still return standard 400, 401, or 415 codes.

10. Express Global Error Handler Example

Centralizing status mapping inside one Express error middleware guarantees that unhandled database exceptions never leak raw stack traces while known domain errors consistently emit RFC 9457 JSON responses:

class ApiProblem extends Error {
  constructor(status, title, detail, type = "about:blank") {
    super(detail);
    this.status = status;
    this.title = title;
    this.type = type;
  }
}

export function errorMiddleware(err, req, res, _next) {
  const status = err instanceof ApiProblem ? err.status : 500;
  const payload = {
    type: err instanceof ApiProblem ? err.type : "https://techcar.online/errors/internal",
    title: err instanceof ApiProblem ? err.title : "Internal Server Error",
    status,
    detail: status === 500 ? "An unexpected server error occurred." : err.message,
    instance: req.originalUrl
  };
  res.status(status).type("application/problem+json").json(payload);
}

Notice how returning a generic detail string whenever status === 500 hides internal SQL table names and file paths from callers while preserving full stack traces inside your private server logs.

Frequently Asked Questions

Should an empty search result return 404 or 200?

Return 200 OK with an empty array ({"items": [], "total": 0}). A search endpoint URL exists and succeeded—it simply matched zero rows. Reserve 404 for requesting a specific non-existent item ID like /users/999999.

What is the difference between 400 Bad Request and 422 Unprocessable Content?

400 means the request cannot even be parsed structurally (broken JSON, missing Content-Length, invalid syntax). 422 means the JSON parsed fine, yet business validation failed (invalid date range, negative quantity, password too short).

Why do browsers trigger an OPTIONS request with 204 or 200 before POST?

That is a CORS preflight request sent automatically by browsers when making cross-origin requests with custom headers like Authorization or Content-Type: application/json. Read our CORS Errors Explained Guide for full details.

Is 404 better than 403 for hiding private documents?

Yes, in security-sensitive multi-tenant APIs! Returning 403 tells an attacker "this invoice ID exists, you just don't own it" (ID enumeration). Returning 404 reveals nothing about whether the ID exists.