error http
HTTP 400 Bad Request
Understanding HTTP 400 Bad Request - the server cannot process the request due to malformed syntax, invalid parameters, or other client errors.
What It Means
HTTP 400 Bad Request indicates that the server cannot or will not process the request due to something perceived to be a client error. This could be malformed request syntax, invalid request message framing, deceptive request routing, or invalid input data.
Common Causes
- Malformed JSON in the request body
- Missing required request parameters or headers
- Invalid query string format
- Request body exceeds expected format
- Invalid URL encoding
- Corrupted or incomplete multipart form data
- Invalid Content-Type header for the request body
How to Fix
Debugging the request
# Use curl to inspect what you're sending
curl -v -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "john@example.com"}'
# Validate JSON before sending
echo '{"name": "John"}' | python3 -m json.tool
Common fixes in JavaScript
// Problem: Sending data without Content-Type header
// Bad
fetch('/api/users', {
method: 'POST',
body: JSON.stringify({ name: 'John' })
});
// Good
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John' })
});
// Problem: Malformed JSON
// Bad - single quotes are not valid JSON
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: "{'name': 'John'}"
});
// Good - use JSON.stringify
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John' })
});
Server-side validation (Express.js)
app.post('/api/users', (req, res) => {
const { name, email } = req.body;
if (!name || !email) {
return res.status(400).json({
error: 'Bad Request',
message: 'Both name and email are required',
fields: {
name: !name ? 'Name is required' : null,
email: !email ? 'Email is required' : null
}
});
}
// Process valid request
});
Python requests
import requests
import json
# Ensure proper JSON encoding
data = {"name": "John", "email": "john@example.com"}
response = requests.post(
"https://api.example.com/users",
json=data # Automatically sets Content-Type and encodes JSON
)
if response.status_code == 400:
print("Bad Request:", response.json())