What is HTTP Response Status Code 412 Precondition Failed?
HTTP response status code 412 Precondition Failed indicates that one or more conditions specified in the request headers were not met. This is often related to headers like If-Match
, If-Unmodified-Since
, or If-None-Match
.
This status code is commonly used in RESTful APIs where the client wants to ensure that a resource has not been modified before proceeding with an update or deletion.
By using preconditions, clients can avoid overwriting changes made by others or ensure that they are working with the most up-to-date version of a resource.
If the preconditions specified in the request do not match the current state of the resource, the server responds with a 412 status code, and the client should adjust the request accordingly.
Example 1: If-Match Header Precondition
# Client sends a PUT request with an If-Match header. PUT /files/12345 HTTP/1.1 Host: api.example.com If-Match: "xyz123" Content-Type: application/json { "name": "New File Name" } # Server Response HTTP/1.1 412 Precondition Failed Date: Wed, 09 Oct 2024 15:15:00 GMT Server: Apache/2.4.41 (Ubuntu) { "error": "The resource has changed since your last request." }
Example 2: If-Unmodified-Since Header
# Client sends a DELETE request with an If-Unmodified-Since header. DELETE /posts/98765 HTTP/1.1 Host: www.example.com If-Unmodified-Since: Wed, 08 Oct 2024 10:00:00 GMT # Server Response HTTP/1.1 412 Precondition Failed Date: Wed, 09 Oct 2024 15:17:00 GMT Server: Nginx/1.18.0 { "error": "The post has been modified since the specified date." }
Summary
The HTTP 412 Precondition Failed status code is used when the conditions specified by the client do not match the state of the resource. It helps prevent actions like updates or deletions if the resource has been changed.
This status code ensures that clients and servers remain in sync about the state of a resource, providing a safeguard against accidental data overwrites.