The HTTP 412 Precondition Failed
status code indicates that one or more conditions specified in the request headers (preconditions) were not met by the server. These preconditions are typically used to ensure that the resource being accessed meets certain criteria before the request is processed. Common precondition headers include If-Match
, If-None-Match
, If-Modified-Since
, and If-Unmodified-Since
.
Key Points
- The server evaluates preconditions in the request headers before processing the request.
- If the preconditions are not met, the server responds with a
412
status code and does not process the request. - This status code is often used for concurrency control and caching mechanisms.
Common Causes
If-Match
Header: TheETag
provided in the request does not match the currentETag
of the resource.If-None-Match
Header: TheETag
provided in the request matches the currentETag
of the resource (used for conditionalGET
requests).If-Modified-Since
Header: The resource has not been modified since the specified date.If-Unmodified-Since
Header: The resource has been modified since the specified date.- Concurrency Control: The request is attempting to modify a resource that has been updated by another client.
How to Fix
- Client-Side Fix:
- Ensure the preconditions in the request headers are correct and up-to-date.
- Fetch the latest version of the resource and retry the request with updated headers.
- Use conditional headers (
If-Match
,If-Unmodified-Since
, etc.) appropriately to avoid conflicts.
- Server-Side Fix:
- Provide clear error messages in the response to help clients understand why the precondition failed.
- Log
412
errors for monitoring and debugging purposes.
Example
If a client sends a request with an If-Match
header that does not match the current ETag
of the resource, the server might respond:
HTTP/1.1 412 Precondition Failed
Content-Type: application/json
{
"error": "Precondition Failed",
"message": "The 'If-Match' header condition was not met.",
"details": {
"currentETag": "12345",
"providedETag": "67890"
}
}
Client-Side Handling
- Check the response body for details about the failed precondition.
- Fetch the latest version of the resource and update the request headers accordingly.
- Use conditional headers to ensure the resource is in the expected state before making changes.
Server-Side Handling
- Return a
412 Precondition Failed
status code when preconditions are not met. - Include detailed information in the response to help clients resolve the issue.
- Use
ETag
andLast-Modified
headers to support conditional requests.
Let me know if you need further clarification!