0
0
Rest-apiConceptBeginner · 3 min read

422 Status Code: Meaning and When to Use It in REST APIs

The 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.

python
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)
Output
Running the server and sending POST /submit with JSON {"age": -5} returns status 422 with {"error": "Age must be a non-negative integer"}.
🎯

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.

Key Takeaways

422 status code means the server understands the request but cannot process it due to invalid data.
Use 422 when the request syntax is correct but the content has semantic errors.
It helps clients fix data issues before resubmitting requests.
422 differs from 400, which signals malformed syntax rather than semantic problems.