← Back to Chapters

400 Bad Request

? 400 Bad Request

? Quick Overview

The 400 Bad Request status code indicates that the server cannot process the request due to a client-side error. This usually happens when the request syntax is invalid, required parameters are missing, or data sent by the client is malformed.

? Key Concepts

  • Client-side HTTP error
  • Request syntax or data is invalid
  • Server rejects the request before processing
  • Common in form submissions and API calls

? Syntax / Theory

In HTTP communication, a 400 Bad Request response is returned when the server detects an issue with the request itself. This error is not related to authentication or authorization, but rather to how the request is structured or what data it contains.

? Code Example(s)

? View Code Example
// Sending an invalid JSON body causing 400 Bad Request
fetch("/api/user", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: "{ name: 'John' }" // Error: Malformed JSON (no quotes on key)
});

? Live Output / Explanation

Server Response

The server returns HTTP/1.1 400 Bad Request because the JSON body is malformed. Proper JSON requires double quotes around keys and string values.

? Interactive Example

Test how a server validates input. The simulated server below expects a Username. If you send it empty or include special characters (like @ or #), it will reject the request.

 
? View Server-Side Logic (Express.js)
// Express.js example returning 400 for invalid input
app.post("/login", (req, res) => {
  const { username } = req.body;
  
  // Validation: Check if empty or contains special chars
  const isValid = /^[a-zA-Z0-9]+$/.test(username);

  if (!username || !isValid) {
    return res.status(400).json({ error: "Invalid username format" });
  }
  
  res.status(200).send("Login successful");
});

? Use Cases

  • Form validation failures
  • Missing required API parameters
  • Invalid JSON or XML payloads
  • Incorrect query string formats

✅ Tips & Best Practices

  • Always validate client input before sending requests
  • Use proper Content-Type headers
  • Return clear error messages with 400 responses
  • Log malformed requests for debugging

? Try It Yourself

  • Send a request with missing parameters to an API
  • Submit invalid JSON and observe the response
  • Implement server-side validation and return 400 errors
  • Fix the request and confirm a successful response