400 Bad Request: Diagnosing Client‑Side Errors
Common Causes of 400 Bad Request
| Cause | Example | How to Fix |
|---|---|---|
| Malformed JSON/XML | Missing quote, trailing comma, unescaped character. | Validate the request body with a JSON/XML validator. |
| Missing required headers | Content-Type or Authorization missing. | Ensure all required headers are present and correctly formatted. |
| Invalid query parameters | Passing a string where a number is expected. | Check the API documentation and correct parameter types. |
| URL encoding issues | Spaces not encoded as %20, unsafe characters not escaped. | Use encodeURIComponent() in JavaScript or urlencode() in PHP. |
| Payload too large | Uploading a file that exceeds the server's limit. | Reduce the payload size or increase the server limit. |
| Unsupported content type | Sending application/xml when the server expects application/json. | Check the Content-Type and Accept headers. |
Example: Invalid JSON
Consider a POST request with an invalid JSON body:
The server responds with:
How to Fix 400 Errors in Different Contexts
- Web APIs: Check the API documentation for required fields, data types, and allowed values. Use tools like Postman to test requests.
- Web browsers: If you see a 400 on a website, it's usually not your fault as an end‑user. Try clearing cookies, refreshing, or contacting the site administrator.
- Mobile apps: Ensure your app is sending the correct headers and payload. Use logging to inspect the outgoing request.
- Command line (cURL): Use the
-vflag to see the full request and response, and verify the syntax.
400 vs. 422 Unprocessable Entity
Both indicate client‑side errors, but they have a subtle difference:
- 400 Bad Request – the request syntax is malformed or cannot be parsed (e.g., invalid JSON, missing headers).
- 422 Unprocessable Entity – the request syntax is valid, but the server cannot process the instructions (e.g., validation errors like "email already exists").
In practice, many APIs use 400 for both cases. For a more detailed approach, use 422 for semantic validation errors.
Frequently Asked Questions
Is 400 Bad Request a server error?
No, it's a client‑side error (4xx). The server is working correctly, but the request from the client is invalid. The fix is on the client side.
Can a 400 Bad Request be cached?
Typically no, because it indicates a client‑specific error. However, some proxies may cache 400 responses for a short time. It's best to set Cache-Control: no-store for 400 responses.
What should I do if I receive a 400 from an API I don't control?
Check the API documentation for correct request format, headers, and parameters. Look at the response body for a detailed error message. Use a tool like Postman or cURL to replicate the request and debug.