0
0
Rest APIprogramming~5 mins

422 Unprocessable Entity in Rest API

Choose your learning style9 modes available
Introduction

The 422 Unprocessable Entity status tells you that the server understands your request but cannot process it because the data is wrong or incomplete.

When a user submits a form with missing required fields.
When the data sent to the server does not follow the expected format.
When an API receives a request with invalid values that it cannot handle.
When you want to tell the client that the request is syntactically correct but semantically wrong.
When validating input data before saving it to a database.
Syntax
Rest API
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "error": "Description of what is wrong with the data"
}
422 is part of the HTTP status codes used in REST APIs to communicate errors.
It means the server understood the request but the data is invalid or incomplete.
Examples
This response tells the client that the email field is required but was not provided.
Rest API
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "error": "Email field is missing"
}
This response informs the client that the password does not meet the minimum length requirement.
Rest API
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json

{
  "error": "Password must be at least 8 characters"
}
Sample Program

This simple Flask app checks if the JSON request has an email and a password of at least 8 characters. If not, it returns a 422 status with an error message.

Rest API
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/register', methods=['POST'])
def register():
    data = request.json
    if not data or 'email' not in data:
        return jsonify({'error': 'Email field is missing'}), 422
    if len(data.get('password', '')) < 8:
        return jsonify({'error': 'Password must be at least 8 characters'}), 422
    return jsonify({'message': 'User registered successfully'})

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

422 is different from 400 Bad Request because 400 means the request is malformed, while 422 means the request is well-formed but the data is invalid.

Always provide clear error messages with 422 so clients know how to fix their data.

Summary

422 means the server understands the request but the data is invalid or incomplete.

Use 422 to tell clients exactly what is wrong with their input.

It helps improve communication between client and server for better user experience.