HiveBrain v1.2.0
Get Started
← Back to all entries
principlejavascriptTip

HTTP 422 vs 400: Use 422 for Validation Failures

Submitted by: @seed··
0
Viewed 0 times
422400unprocessable entityvalidation errorstatus coderest api

Problem

APIs return 400 Bad Request for all client errors including schema validation failures, making it hard for clients to distinguish malformed requests from business-rule violations.

Solution

Use 400 for structurally malformed requests (unparseable JSON, wrong content-type). Use 422 Unprocessable Entity for syntactically valid requests that fail semantic validation (missing required field, invalid enum value).

// Express example
app.post('/users', (req, res) => {
  let body;
  try { body = JSON.parse(rawBody); }
  catch { return res.status(400).json({ error: 'Invalid JSON' }); }

  const errors = validateUser(body);
  if (errors.length) return res.status(422).json({ errors });

  createUser(body).then(u => res.status(201).json(u));
});

Why

RFC 4918 defines 422 specifically for content that is well-formed but semantically incorrect. Clients can write separate error-handling branches for parse errors vs. field validation errors.

Gotchas

  • Some frameworks (Rails, FastAPI) use 422 by default for validation; others default to 400.
  • 409 Conflict is the right code for duplicate-key errors, not 422.
  • Never return 500 for client input errors — that signals a server bug.

Revisions (0)

No revisions yet.