422 Status Code: Meaning and When to Use It in REST APIs
422 Unprocessable Entity status code means the server understands the request's syntax but cannot process the instructions because of semantic errors. It is used when the request is well-formed but contains invalid data that prevents successful processing.How It Works
Imagine you send a letter with all the right words and grammar, but the message itself doesn't make sense or has wrong details. The 422 Unprocessable Entity status code works like a polite reply from the server saying, "I understand your letter perfectly, but I can't act on it because something is wrong with the content."
In REST APIs, this means the server received your request and understood its format (like JSON or XML), but the data inside has problems. For example, a required field might be missing, or a value might be out of allowed range. The server refuses to process the request until you fix these issues.
Example
This example shows a simple REST API endpoint in Python using Flask that returns a 422 status code when the input data is invalid.
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): data = request.get_json() if not data or 'age' not in data: return jsonify({'error': 'Missing age field'}), 422 if not isinstance(data['age'], int) or data['age'] < 0: return jsonify({'error': 'Age must be a non-negative integer'}), 422 return jsonify({'message': 'Data accepted'}), 200 if __name__ == '__main__': app.run(debug=True)
When to Use
Use the 422 Unprocessable Entity status code when the client sends a request that is syntactically correct but semantically wrong. This means the server understands the request format but cannot process it due to invalid or missing data.
Common real-world cases include:
- Form submissions with missing required fields.
- Data that violates business rules, like negative age or invalid email format.
- Requests where the content type is correct but the values are not acceptable.
This helps clients know they need to fix their data before retrying.
Key Points
- 422 means the request is well-formed but has semantic errors.
- It differs from
400 Bad Request, which is for malformed syntax. - Useful for validating user input and business rules.
- Helps clients correct data without guessing.