HTTP status codes are useful only when they communicate a clear outcome and lead the client toward the right next action. This practical reference explains which status code to use, how to structure JSON error responses, and how to troubleshoot failed REST API requests without guessing.
Overview
An HTTP response has three parts that matter during API troubleshooting: the status code, response headers, and response body. The status code gives a broad classification of the result; headers can provide details such as authentication challenges, rate-limit information, caching instructions, or retry timing; and the body should explain the problem in a machine-readable way.
Use status codes consistently. A successful response should not return 200 OK merely because the server stayed available if the requested operation failed. Likewise, a malformed request is usually a client error, not a server error. Accurate classification helps client developers decide whether to correct input, refresh credentials, wait and retry, or investigate the service.
| Class | Common codes | Typical meaning | Usual client action |
|---|---|---|---|
| 2xx success | 200, 201, 202, 204 | The request was handled successfully or accepted for processing. | Read the response, follow the documented workflow, or continue. |
| 3xx redirection | 301, 302, 303, 304, 307, 308 | The client may need a different location or can use a cached representation. | Follow redirects only when appropriate and inspect Location or caching headers. |
| 4xx client error | 400, 401, 403, 404, 405, 409, 422, 429 | The request cannot be completed as submitted or authorized. | Fix the request, credentials, resource state, or request rate. |
| 5xx server error | 500, 502, 503, 504 | The server or an upstream dependency could not complete a valid request. | Capture diagnostics, apply bounded retries where safe, and escalate persistent failures. |
The exact choice depends on the API contract. For example, 400 Bad Request is commonly used for malformed syntax or invalid request structure, while 422 Unprocessable Content can describe a well-formed request whose field values fail validation. Pick one convention, document it, and apply it across endpoints.
Checklist by scenario
When designing a successful endpoint
- Use
200 OKwhen the operation completes and the response contains a representation or result. - Use
201 Createdwhen a resource is created. Include aLocationheader when the new resource has a distinct URL, and return the representation if that is part of the contract. - Use
202 Acceptedwhen processing has been accepted but is not complete. Explain how the client can check progress if the workflow is asynchronous. - Use
204 No Contentwhen the operation succeeds and there is intentionally no response body, such as a successful deletion.
When the request is invalid
- Return
400 Bad Requestfor invalid JSON, missing required request structure, unsupported syntax, or a request that cannot be parsed. - Return
422 Unprocessable Contentfor field-level validation failures when the JSON and overall request shape are valid. - Return
405 Method Not Allowedwhen the resource exists but does not support the requested method. AnAllowheader can identify supported methods. - Return
409 Conflictwhen the request conflicts with the current resource state, such as attempting to create a duplicate or update an outdated version.
When authentication or authorization fails
- Use
401 Unauthorizedwhen the request lacks valid authentication credentials. The response should not imply that changing unrelated request fields will solve the problem. - Use
403 Forbiddenwhen the server understands the caller but will not permit the requested action. Avoid exposing sensitive authorization details. - Use
404 Not Foundwhen the resource does not exist or when the API intentionally does not reveal whether a protected resource exists.
When a client is sending requests too quickly
Use 429 Too Many Requests when rate limits apply. Return a clear error code in the body and, where supported by the API contract, include Retry-After with a delay or date. Clients should respect that guidance instead of retrying immediately in a tight loop.
When the service or an upstream dependency fails
- Use
500 Internal Server Errorfor an unexpected failure that is not better represented by a more specific status. - Use
502 Bad Gatewaywhen a gateway or proxy receives an invalid response from an upstream service. - Use
503 Service Unavailablewhen the service is temporarily unable to handle the request, including planned or unplanned capacity issues. - Use
504 Gateway Timeoutwhen a gateway does not receive a timely response from an upstream service.
Do not expose stack traces, SQL fragments, access tokens, or internal hostnames in production responses. Put correlation identifiers in logs and return a safe reference value to help support teams connect the client error to server-side diagnostics.
Use a consistent JSON error response
A predictable response makes errors easier to handle across browsers, command-line clients, background jobs, and SDKs. The following shape is one practical convention:
{"type":"https://api.example.com/problems/validation-error","title":"Request validation failed","status":422,"code":"INVALID_INPUT","detail":"One or more fields are invalid.","instance":"/requests/7f3a","errors":[{"field":"email","message":"Enter a valid email address."}],"requestId":"req_12345"}Keep stable machine-readable fields such as code separate from human-facing text. A client can branch on INVALID_INPUT while the wording of detail changes. Do not assume every client can safely display server-provided text without escaping it.
What to double-check
Follow the request from client to server
- Confirm the final URL, HTTP method, query parameters, and body after any client-side transformations.
- Check the
Content-TypeandAcceptheaders. A server may reject JSON sent without the correct media type or return a representation the client cannot parse. - Inspect authentication headers, token expiry, required scopes, and whether a proxy or browser removed sensitive headers.
- Record the complete status line, relevant response headers, and sanitized body. A JSON formatter can make nested error payloads easier to inspect; see the JSON formatting and validation guide.
- Compare the failing request with a known-good request. Change one variable at a time so the diagnosis remains testable.
Apply retries carefully
Retrying is appropriate only when failure may be temporary and repeating the operation is safe. Start with a short timeout, bounded exponential backoff, and jitter so many clients do not retry at the same moment. Honor Retry-After when supplied. Consider retries for transient connection failures, some 408, 429, and 5xx responses, but use the API contract as the deciding authority.
Be especially cautious with non-idempotent operations such as creating a payment or submitting an order. A timeout does not prove that the server did nothing. Use an idempotency key where the API supports one, or first check whether the operation completed before sending it again. Never retry a permanent 400, 401, 403, or validation error unchanged.
Separate client, gateway, and application evidence
A browser's network panel, a command-line request, and server logs can show different parts of the same failure. If a request never reaches the application, investigate DNS, TLS, routing, proxy, firewall, or browser policy issues. If it reaches the server and receives a 4xx response, inspect validation and authorization. If the application returns a 5xx response, use the request ID and timestamp to trace dependency calls, timeouts, and exceptions. The API testing helpers workflow provides a useful companion process for checking encoded parameters and request details.
Common mistakes
- Returning 200 for every outcome: This forces clients to parse business logic from the body and makes monitoring less meaningful.
- Using 401 for every permission problem: Missing or invalid authentication and authenticated-but-forbidden actions are different cases.
- Leaking implementation details: Debug messages, database errors, and stack traces can reveal information that belongs only in protected logs.
- Changing error shapes between endpoints: Inconsistent field names make SDKs and frontend error handling unnecessarily complex.
- Retrying without limits: Unbounded retries can amplify an outage, duplicate side effects, and hide the original failure.
- Ignoring redirects and proxies: A client may report a final status while the important clue is an earlier redirect, gateway header, or upstream response.
- Confusing transport success with application success: A completed HTTP exchange can still contain a 4xx or 5xx result. Check the status code before treating the call as successful.
When to revisit
Review this checklist whenever you add an endpoint, change authentication, introduce an asynchronous job, or alter a gateway, proxy, timeout, or rate-limit policy. Revisit it during incident reviews and before major planning cycles so status codes, retry behavior, and error schemas remain consistent across services.
Also update the reference when your framework, HTTP client, API gateway, or observability workflow changes. Test the documented behavior rather than relying only on implementation defaults: send malformed JSON, invalid credentials, missing fields, duplicate requests, expired resources, rate-limited traffic, and simulated upstream timeouts. Confirm the status code, headers, safe response body, logging, and client retry decision for each case.
For a final implementation pass, ask three questions: does the status code describe what actually happened, can a client determine its next action without reading server internals, and can an operator trace the failure without exposing sensitive data? If the answer to all three is yes, the endpoint has a strong foundation for predictable REST API error handling.