- Home
- HTTP Status Codes
- 422 Unprocessable Entity
Status Code
422 Unprocessable Entity
Learn what 422 Unprocessable Entity means for semantically invalid requests. Understand validation errors, the difference from 400, and proper error handling.
What is a 422 Error?
TL;DR: 422 Unprocessable Entity means valid syntax but invalid data. Check the response for validation error details.
A 422 Unprocessable Entity status code means your request is perfectly formatted and the server understands it, but the data you sent doesn’t make sense or violates business rules. Think of it like filling out a form correctly but putting your birthday as a future date—the form is filled out properly, but the information itself is logically wrong.
The server can parse your request just fine, but the content fails validation or semantic checks.
When Does This Happen?
You’ll encounter a 422 error in these common situations:
1. Data Validation Failures
You send: {"email": "not-an-email", "age": -5}
Validation: Email format invalid, age must be positive
Result: 422 Unprocessable Entity
2. Business Rule Violations
You try: Creating order for out-of-stock item
Rule: Can't order items with 0 inventory
Result: 422 Unprocessable Entity
3. Missing Required Fields
You send: {"name": "John"}
Required: name, email, and password fields
Result: 422 Unprocessable Entity
4. Invalid Data Relationships
You try: Assigning user to non-existent team
Check: Team ID doesn't exist in database
Result: 422 Unprocessable Entity
5. Format Correct but Semantically Wrong
You send: {"start_date": "2024-12-01", "end_date": "2024-01-01"}
Issue: End date is before start date
Result: 422 Unprocessable Entity
Example Response
When data validation fails, the server responds like this:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
Content-Length: 245
{
"error": "Validation failed",
"message": "The request contains invalid data",
"errors": [
{
"field": "email",
"message": "Must be a valid email address",
"received": "not-an-email"
},
{
"field": "age",
"message": "Must be a positive number",
"received": -5
}
]
}
```text
Key parts of this response:
- **422 Unprocessable Entity** - The status code and reason
- **Content-Type** - Format of the validation errors
- **Errors array** - Detailed information about each validation failure
- **Field-specific messages** - Exactly what's wrong with each field
## Real-World Examples
**Example 1: User Registration Validation**
```http
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
{
"username": "ab",
"email": "invalid-email",
"password": "123",
"age": 150
}
Response:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": "Validation failed",
"message": "User data contains errors",
"errors": [
{
"field": "username",
"code": "TOO_SHORT",
"message": "Username must be at least 3 characters",
"min_length": 3,
"received_length": 2
},
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Email address format is invalid",
"pattern": "user@domain.com"
},
{
"field": "password",
"code": "TOO_WEAK",
"message": "Password must be at least 8 characters with mixed case",
"requirements": ["min 8 chars", "uppercase", "lowercase", "number"]
},
{
"field": "age",
"code": "OUT_OF_RANGE",
"message": "Age must be between 13 and 120",
"min": 13,
"max": 120,
"received": 150
}
]
}
```text
**Example 2: Business Logic Violation**
```http
POST /api/orders HTTP/1.1
Host: shop.example.com
Content-Type: application/json
{
"product_id": 123,
"quantity": 5,
"customer_id": 456
}
Response:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": "Business rule violation",
"message": "Order cannot be processed",
"errors": [
{
"field": "quantity",
"code": "INSUFFICIENT_STOCK",
"message": "Only 2 items available in stock",
"requested": 5,
"available": 2,
"suggestion": "Reduce quantity to 2 or less"
}
],
"alternative_actions": [
"Add item to wishlist",
"Get notified when back in stock"
]
}
```text
## How to Handle 422 Errors
**As a Developer:**
- Parse the errors array to show specific field issues
- Highlight problematic fields in your UI
- Provide clear, actionable error messages to users
- Implement client-side validation to catch issues early
**As a User:**
- Read the error messages carefully
- Fix the specific issues mentioned
- Check that all required fields are filled
- Ensure data makes logical sense
## 422 vs Other Similar Codes
| Code | Meaning | What's Different |
| ------- | --------------------------------- | ------------------------------------------------ |
| **422** | Data is invalid or violates rules | Request format is correct, data content is wrong |
| **400** | Bad request format | Request syntax or structure is malformed |
| **415** | Unsupported media type | Server doesn't support the data format |
| **409** | Conflict with current state | Data conflicts with existing resources |
| **413** | Payload too large | Request size exceeds limits |
## Common Validation Scenarios
**❌ Not handling validation errors properly**
```javascript
// This doesn't help users fix their mistakes
fetch('/api/users', {
method: 'POST',
body: JSON.stringify(userData)
}).then((response) => {
if (!response.ok) {
throw new Error('Something went wrong')
}
})
✅ Proper validation error handling
// This provides specific feedback
fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
}).then(async (response) => {
if (response.status === 422) {
const errorData = await response.json()
// Show specific field errors
errorData.errors.forEach((error) => {
showFieldError(error.field, error.message)
})
return
}
if (!response.ok) {
throw new Error('Request failed')
}
return response.json()
})
function showFieldError(fieldName, message) {
const field = document.querySelector(`[name="${fieldName}"]`)
const errorElement = field.nextElementSibling
errorElement.textContent = message
field.classList.add('error')
}
```javascript
## Server-Side Validation Example
**Express.js with validation:**
```javascript
const { body, validationResult } = require('express-validator')
app.post(
'/api/users',
// Validation rules
body('email').isEmail().withMessage('Must be a valid email'),
body('age').isInt({ min: 13, max: 120 }).withMessage('Age must be 13-120'),
body('username').isLength({ min: 3 }).withMessage('Username too short'),
(req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(422).json({
error: 'Validation failed',
message: 'Request contains invalid data',
errors: errors.array().map((err) => ({
field: err.path,
message: err.msg,
received: err.value
}))
})
}
// Process valid data...
}
)
Best Practices for 422 Responses
Include specific field information:
{
"errors": [
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Email must be in format user@domain.com",
"received": "not-email"
}
]
}
```text
**Provide helpful suggestions:**
```json
{
"errors": [
{
"field": "password",
"message": "Password too weak",
"requirements": ["8+ characters", "uppercase", "lowercase", "number"],
"strength_score": 2,
"suggestions": ["Add uppercase letters", "Include numbers"]
}
]
}
Try It Yourself
Visit our request builder and test validation:
- Set method to POST
- Set path to /api/users
- Send invalid data (bad email, negative age)
- Examine the detailed 422 response
Related Status Codes
- 400 Bad Request - Request format is wrong
- 409 Conflict - Data conflicts with existing state
- 415 Unsupported Media Type - Wrong data format
- 413 Payload Too Large - Request size too large
Frequently Asked Questions
What does 422 Unprocessable Entity mean?
A 422 error means the request is syntactically correct but contains semantic errors. The server understands the format but the data fails validation rules, like an email field containing an invalid email address.
What is the difference between 422 and 400?
400 means the request is malformed or has syntax errors. 422 means the syntax is correct but the content is semantically invalid. Use 400 for parsing errors, 422 for validation errors.
How do I fix a 422 error?
Check the response body for validation error details. Fix the invalid data fields according to the API requirements. Common issues include invalid formats, out-of-range values, or missing required relationships.
When should I use 422 vs 400 in my API?
Use 400 when the request cannot be parsed (invalid JSON, wrong content type). Use 422 when the request parses correctly but fails business validation (invalid email, negative age, duplicate username).