The 422 Unprocessable Entity
status code is a member of the 4xx class of HTTP status codes, which are designated for client errors. It indicates that the server has understood the content type of the request entity and the syntax of the request is correct, but it was unable to process the contained instructions.
This status code is primarily used in the context of Web Distributed Authoring and Versioning (WebDAV) extensions to HTTP, as defined in RFC 4918. However, it can also be applicable to other situations where a request cannot be processed due to semantic issues.
When to Use 422 Unprocessable Entity
The 422 Unprocessable Entity
status code should be used in scenarios where the server is unable to process the request due to semantic errors, rather than syntactic errors. Some common use cases include:
- The client has provided a request that contains well-formed data, but the data is invalid or inconsistent with the resource state.
- The request violates data validation rules or constraints imposed by the server.
- The client attempts to create a resource with a duplicate identifier or other conflicting property.
In these cases, the server should return a 422 Unprocessable Entity
status code along with a response body that provides additional information about the error(s) encountered.
Example: Request and Response
Consider a scenario where a client sends a POST
request to create a new user on a server. The request includes a JSON payload with the user’s information, but the provided email address is already associated with an existing user.
Request:
POST /users HTTP/1.1
Host: example.com
Content-Type: application/json
Content-Length: 68
{
"name": "John Doe",
"email": "johndoe@example.com",
"password": "123456"
}
In this case, the server should respond with a 422 Unprocessable Entity
status code, indicating that the request cannot be processed due to a semantic error (i.e., the duplicate email address).
Response:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
Content-Length: 76
{
"errors": [
{
"field": "email",
"message": "Email address is already in use."
}
]
}
The response body includes a JSON object that provides more information about the error, such as the field in question (email
) and a human-readable error message.
Summary
The 422 Unprocessable Entity
HTTP status code is a valuable tool for communicating semantic errors in client requests. By using this status code, servers can provide clients with specific information about why a request cannot be processed, allowing them to address the issue and resubmit the request.
Remember to use the 422 Unprocessable Entity
status code when the server understands the request’s content type and syntax but is unable to process the contained instructions due to semantic issues. This will help ensure clear and effective communication between the client and server in HTTP-based applications.