What is HTTP 400 Bad Request?

HTTP 400 Bad Request indicates that the server cannot process the request due to a client error. This means there's something wrong with the request syntax, invalid request message framing, or deceptive request routing that prevents the server from understanding what the client is asking for.

Unlike server errors (5xx), a 400 error suggests the problem is on the client side and the same request should not be repeated without modification.

Common Causes of HTTP 400 Errors

cURL Examples That Trigger 400 Errors

Example 1: Malformed JSON

curl -X POST "https://api.example.com/users" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "[email protected]"  # Missing closing brace
  }'

Response:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": "Invalid JSON syntax",
  "message": "Unexpected end of JSON input"
}

Example 2: Missing Required Fields

curl -X POST "https://api.example.com/users" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe"
  }'

Response:

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": "Validation failed",
  "message": "Missing required field: email"
}

Example 3: Invalid Data Type

curl -X POST "https://api.example.com/users" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "[email protected]",
    "age": "twenty-five"
  }'

Correct cURL Examples

Properly Formatted JSON Request

curl -X POST "https://api.example.com/users" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "name": "John Doe",
    "email": "[email protected]",
    "age": 25
  }'

URL-Encoded Form Data

curl -X POST "https://api.example.com/users" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "name=John%20Doe&email=john%40example.com&age=25"

How to Debug HTTP 400 Errors

1. Use Verbose Output

Enable verbose mode to see the full request and response details:

curl -v -X POST "https://api.example.com/users" \
  -H "Content-Type: application/json" \
  -d '{"name":"John","email":"[email protected]"}'

2. Validate JSON Syntax

Use online JSON validators or command-line tools to check your JSON:

# Using jq to validate JSON
echo '{"name":"John","email":"[email protected]"}' | jq .

3. Check Request Headers

Ensure all required headers are present and correct:

curl -X POST "https://api.example.com/users" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -H "User-Agent: MyApp/1.0" \
  -d '{"name":"John","email":"[email protected]"}'

Handling HTTP 400 in Different Languages

Python with requests

import requests
import json

try:
    data = {
        "name": "John Doe",
        "email": "[email protected]",
        "age": 25
    }
    
    response = requests.post(
        'https://api.example.com/users',
        json=data,
        headers={'Content-Type': 'application/json'}
    )
    
    if response.status_code == 400:
        error_data = response.json()
        print(f"Bad Request: {error_data.get('message', 'Unknown error')}")
    elif response.status_code == 200:
        print("Success:", response.json())
    else:
        print(f"Unexpected status code: {response.status_code}")
        
except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
except json.JSONDecodeError as e:
    print(f"Invalid JSON response: {e}")

JavaScript with fetch

const userData = {
  name: "John Doe",
  email: "[email protected]",
  age: 25
};

fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  },
  body: JSON.stringify(userData)
})
.then(response => {
  if (response.status === 400) {
    return response.json().then(errorData => {
      throw new Error(`Bad Request: ${errorData.message || 'Invalid request'}`);
    });
  }
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }
  return response.json();
})
.then(data => {
  console.log('Success:', data);
})
.catch(error => {
  console.error('Request failed:', error.message);
});

Preventing HTTP 400 Errors

Best Practices to Avoid 400 Errors:

  • Validate input data before sending requests
  • Use proper JSON formatting and validation tools
  • Include all required fields as specified in API documentation
  • Set correct Content-Type headers for your payload
  • URL-encode special characters in query parameters
  • Test with API documentation examples first
  • Implement client-side validation in your applications

Common 400 Error Scenarios and Solutions

Scenario 1: File Upload Issues

Problem: Incorrect Content-Type for file uploads

# Incorrect - using JSON content type for file upload
curl -X POST "https://api.example.com/upload" \
  -H "Content-Type: application/json" \
  -F "[email protected]"

# Correct - multipart form data for file upload
curl -X POST "https://api.example.com/upload" \
  -F "[email protected]" \
  -F "description=Important document"

Scenario 2: Query Parameter Encoding

Problem: Special characters not properly encoded

# Incorrect - unencoded special characters
curl -X GET "https://api.example.com/[email protected]"

# Correct - properly encoded
curl -X GET "https://api.example.com/search?q=user%40example.com"

Important: Always refer to the API documentation for specific requirements regarding data formats, required fields, and acceptable values. Different APIs may have different validation rules.

Tools for Testing and Debugging

Pro Tip: Use our cURL to Code Converter to generate properly formatted requests in your preferred programming language and avoid common syntax errors!