HTTP 400 Bad Request

The server cannot process your request because it contains invalid syntax, missing required fields, or malformed data. This is a client-side error, meaning the problem is in the request you sent, not on the server.

What Is HTTP 400 Bad Request?

HTTP 400 Bad Request is a client error status code indicating the server cannot process the request due to something the server perceives as a client error. This could be malformed request syntax, invalid request message framing, or deceptive request routing. The 400 code is a generic catch-all for client-side errors that do not fit into more specific 4xx categories like 401 (authentication), 403 (authorization), or 404 (not found).

In modern API development, 400 errors most commonly occur when the request body contains invalid JSON, required fields are missing, data types do not match the expected schema, or query parameters are formatted incorrectly. Well-designed APIs return detailed error messages in the 400 response body, listing the specific fields that failed validation and what values were expected. This makes 400 errors much easier to debug compared to APIs that return generic error messages.

Developers encounter 400 errors frequently during API integration work, especially when dealing with strict input validation. The error is always the client's responsibility to fix, whether that means correcting the JSON syntax, adding missing required fields, converting data types, or adjusting the Content-Type header. Unlike server errors (5xx), a 400 error indicates that retrying the exact same request will produce the same error. The request itself must be corrected before resubmitting.

Common Causes

Malformed JSON Body

The request body contains invalid JSON, such as missing quotes, trailing commas, or incorrect nesting. The server's JSON parser rejects the payload before the handler even runs.

Missing Required Parameters

The request is missing fields that the endpoint requires. For example, submitting a user creation request without an email address when the API mandates one.

Invalid Content-Type Header

The Content-Type header does not match the body format. Sending JSON data with Content-Type: text/plain causes the server to misinterpret the body.

Query Parameter Type Mismatch

A query parameter expected to be a number is sent as a string, or a date parameter is sent in the wrong format. The server's validation layer rejects the invalid type.

How to Fix

Validate JSON Syntax

Use a JSON formatter or validator to check your request body for syntax errors. Common mistakes include trailing commas, single quotes instead of double quotes, and unescaped special characters.

Check API Documentation

Review the endpoint documentation to verify all required fields, their types, and formatting requirements. Pay attention to required versus optional parameters and accepted value ranges.

Set Correct Content-Type

Ensure your Content-Type header matches the body format. Use application/json for JSON payloads, application/x-www-form-urlencoded for form data, and multipart/form-data for file uploads.

Log the Full Error Response

Many APIs include detailed validation errors in the 400 response body. Read the error message carefully — it often tells you exactly which field is invalid and what value was expected.

Code Examples

Express.js

// Express.js — handle and return descriptive 400 errors
const express = require('express');
const app = express();
app.use(express.json());

app.post('/api/users', (req, res) => {
  const { email, name, age } = req.body;
  const errors = [];

  if (!email) errors.push('email is required');
  if (!name) errors.push('name is required');
  if (age !== undefined && (typeof age !== 'number' || age < 0)) {
    errors.push('age must be a positive number');
  }
  if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    errors.push('email format is invalid');
  }

  if (errors.length > 0) {
    return res.status(400).json({
      error: 'Bad Request',
      message: 'Validation failed',
      details: errors
    });
  }

  // ... create user
  res.status(201).json({ id: 1, email, name, age });
});

// Catch JSON parse errors globally
app.use((err, req, res, next) => {
  if (err.type === 'entity.parse.failed') {
    return res.status(400).json({
      error: 'Bad Request',
      message: 'Invalid JSON in request body'
    });
  }
  next(err);
});

Flask (Python)

# Flask — handle and return descriptive 400 errors
from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/api/users', methods=['POST'])
def create_user():
    data = request.get_json(silent=True)

    if data is None:
        return jsonify(
            error='Bad Request',
            message='Invalid JSON in request body'
        ), 400

    errors = []
    if not data.get('email'):
        errors.append('email is required')
    if not data.get('name'):
        errors.append('name is required')
    if 'age' in data and (not isinstance(data['age'], int) or data['age'] < 0):
        errors.append('age must be a positive number')

    if errors:
        return jsonify(
            error='Bad Request',
            message='Validation failed',
            details=errors
        ), 400

    # ... create user
    return jsonify(id=1, email=data['email'], name=data['name']), 201

@app.errorhandler(400)
def bad_request(e):
    return jsonify(error='Bad Request', message=str(e)), 400

Frequently Asked Questions

What causes a 400 Bad Request error?

The most common causes are malformed JSON in the request body, missing required fields, incorrect data types, wrong Content-Type header, and improperly encoded URL parameters. The error always indicates a problem with the request, not the server.

What is the difference between 400 and 422?

HTTP 400 means the request is syntactically invalid and cannot be parsed. HTTP 422 Unprocessable Entity means the request syntax is correct but the content is semantically invalid, such as submitting an email field with a phone number value.

Should I return 400 or 404 for a missing resource?

Use 404 when the URL itself is valid but the resource does not exist. Use 400 when the request structure is wrong, like a malformed URL path, invalid query parameters, or a bad request body.

How can I debug a 400 error from an API?

First, check the response body for specific error messages. Then validate your JSON syntax with a JSON validator, verify required fields against the API documentation, and test with a minimal request to isolate the failing field.

Can browser extensions cause 400 errors?

Yes. Browser extensions that modify request headers, inject cookies, or alter form data can cause 400 errors. Try the request in an incognito window with extensions disabled to rule this out.

Monitor Your APIs & Services

Get instant alerts when your endpoints go down. 60-second checks, free forever.

Start Monitoring Free →