422 Unprocessable Entity
Client Error - Well-formed but semantically invalid
HTTP 422 Unprocessable Entity
What It Means
The HTTP 422 Unprocessable Entity status code indicates that the server understands the content type and the request syntax is correct, but it was unable to process the contained instructions due to semantic errors.
400 vs 422: When to Use Each
- 400: Malformed syntax — can't even parse the request
- 422: Valid syntax, but values don't make sense
Examples
| Error Type | Status |
|---|---|
Invalid JSON: {name: "test" |
400 |
| Missing required field | 422 |
| Invalid email format | 422 |
| Age is negative number | 422 |
| End date before start date | 422 |
Example Response
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": "Validation Error",
"message": "The request contains invalid data",
"errors": [
{
"field": "email",
"message": "Invalid email format"
},
{
"field": "age",
"message": "Must be a positive number"
},
{
"field": "end_date",
"message": "Must be after start_date"
}
]
}
Implementation
Express.js with express-validator
const { body, validationResult } = require('express-validator');
app.post('/api/users', [
body('email').isEmail().withMessage('Invalid email format'),
body('age').isInt({ min: 0 }).withMessage('Must be positive'),
body('name').notEmpty().withMessage('Name is required'),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({
error: 'Validation Error',
errors: errors.array()
});
}
// Process valid request...
});
Python FastAPI
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, EmailStr, validator
class User(BaseModel):
email: EmailStr
age: int
@validator('age')
def age_must_be_positive(cls, v):
if v < 0:
raise ValueError('Age must be positive')
return v
# FastAPI automatically returns 422 for validation errors
Best Practices
- Return all validation errors, not just the first one
- Include the field name with each error
- Provide clear, actionable error messages
- Use consistent error response format across your API
- Document expected formats in your API documentation
Note on Standards
422 is from WebDAV (RFC 4918) but is widely adopted by REST APIs. Some APIs use 400 for all client errors. Both are valid — just be consistent.