HTTP Status Code 428 – Precondition Required
Description
The HTTP 428 Precondition Required status code indicates that the origin server requires the request to be conditional. This response is sent by servers that require a specific precondition to be fulfilled before processing the request, typically using the If-Match
or If-Unmodified-Since
headers. The main purpose is to prevent the “lost update” problem, where a client may inadvertently overwrite changes made by another client.
Example 1: Using If-Match Header
A client wants to update a resource on the server. To ensure that it does not overwrite any recent changes, it includes an If-Match
header with the ETag value of the version it last retrieved.
PUT /resource/123 HTTP/1.1 Host: example.com If-Match: "34f8dsf34f" Content-Type: application/json { "name": "Updated Resource" }
If the ETag value of the resource on the server does not match "34f8dsf34f"
, the server will respond with a 428 Precondition Required status, indicating that the client’s precondition failed.
Example 2: Using If-Unmodified-Since Header
Another scenario is when a client updates a resource but wants to ensure no changes have occurred since a certain date. The client uses the If-Unmodified-Since
header.
PUT /document/456 HTTP/1.1 Host: example.com If-Unmodified-Since: Wed, 21 Oct 2021 07:28:00 GMT Content-Type: application/json { "title": "Updated Document" }
If the resource has been modified after the specified date, the server will reply with a 428 Precondition Required status, indicating that the update cannot proceed without meeting the precondition.
Response Example 3
# Client sends a request example. GET /example HTTP/1.1 Host: www.example.com # Server Response HTTP/1.1 428 428 Precondition Required Date: Wed, 09 Oct 2024 23:07:08 GMT Server: ExampleServer/1.0 Content-Type: application/json { "error": "Description of the error for 428" }
Example 4: Another Scenario
# Client sends another example request. POST /another-example HTTP/1.1 Host: www.example.com # Server Response HTTP/1.1 428 428 Precondition Required Date: Wed, 09 Oct 2024 23:07:08 GMT Server: ExampleServer/1.0 Content-Type: application/json { "error": "Detailed message for 428" }
Summary
The 428 Precondition Required status code is a mechanism to ensure that operations on a resource are performed safely by requiring conditions to be met before they are executed. It is particularly useful in concurrent environments to prevent data from being unintentionally overwritten. By utilizing headers like If-Match
and If-Unmodified-Since
, clients can specify preconditions that must be satisfied for the request to succeed, thus providing a robust approach to handling concurrent modifications.