Skip to main content

Conditional requests

Two clients that read the same order and both change it overwrite each other: the second change undoes the first, and neither client learns of it. With conditional requests (RFC 9110, section 13), every answer that shows a resource carries its version in ETag, a change names the version it was made against in If-Match, and a change against a version the resource no longer has is refused with 412. A client that reads the resource again names the version it holds in If-None-Match and gets 304 without a body while nothing has changed.

Protect a route​

Give the routes of a resource the middleware. It reads the resource from the parameters of the route, so route model binding has to have run before it, which the api middleware group of routes/api.php does. Laravel puts /api in front of every path there, so these routes answer /api/orders/{order}:

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\JsonApi\JsonApiResource;
use Illuminate\Support\Facades\Route;
use Pushery\HttpApi\Preconditions\Conditional;

Route::get('/orders/{order}', function (Order $order) {
return new JsonApiResource($order);
})->middleware(['auth:sanctum', Conditional::class]);

Route::patch('/orders/{order}', function (Request $request, Order $order) {
$order->update(['note' => $request->input('data.attributes.note')]);

return new JsonApiResource($order);
})->middleware(['auth:sanctum', Conditional::class]);

A client reads the order and keeps its tag:

GET /api/orders/1042 HTTP/1.1

HTTP/1.1 200 OK
Content-Type: application/vnd.api+json
ETag: "5c0e3f6a9b8d47e1a2f4c6b8d0e1f3a5"

It sends the tag with its change. If another client has changed the order in between, the change is refused, and the order stays as the other client left it:

PATCH /api/orders/1042 HTTP/1.1
If-Match: "5c0e3f6a9b8d47e1a2f4c6b8d0e1f3a5"
Content-Type: application/vnd.api+json

{"data": {"type": "orders", "id": "1042", "attributes": {"note": "Leave at the door"}}}

What the client gets​

The requestThe answer
a GET or HEAD of a resourcethe route's own answer, with the resource's tag in ETag
a GET or HEAD whose If-None-Match names that tag304 without a body
a PATCH, PUT or DELETE whose If-Match names the current tagthe route's own answer, with the new tag in ETag
a PATCH, PUT or DELETE whose If-Match names an older version412 precondition_failed
a PATCH, PUT or DELETE without If-Match428 precondition_required
a POST whose answer shows the resource it createdthe route's own answer, with the new resource's tag in ETag

Both refusals are JSON:API errors from the error catalog that name If-Match in source.header, and in neither case has the route run. After a 412, the client reads the resource again before it decides on its change.

If-None-Match compares weakly, so W/"…" names a tag as well as the tag itself, and * names any. If-Match compares strongly, as RFC 9110 has it: a weak tag never holds, * holds for every resource that still exists, and a list holds when one tag in it is the current one.

The tag​

The tag is made from the resource's row as the database holds it, read again by its key whenever an answer is tagged or a change is compared. Every change that reaches the database changes it, two within the same second included, and so does a change made past the model, by a queued job or a statement of its own. The representation a request asks for with include or fields changes nothing, so one tag holds for every representation of a resource, and a cache in front of the application that keeps an answer under these parameters finds the same tag in each.

An answer is tagged where it is 200 or 201 and shows one model: a JsonApiResource of it, the model returned from the route, or response()->json($model). A collection, an answer without a model and an answer whose route set an ETag of its own keep what the route gave them.

The row is signed with the application key, so a tag gives nothing away about the columns it covers, hidden ones included. A new APP_KEY changes every tag once: each client then reads its resource again before the next change.

A version of your own​

Every column counts, a counter of views as much as the price. A model whose version is one column, raised with every change that matters, names it by implementing HasEntityVersion:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Pushery\HttpApi\Preconditions\HasEntityVersion;

class Order extends Model implements HasEntityVersion
{
public function entityVersion(): string
{
return (string) $this->version;
}
}

Its tag then follows version, read again from the database like the row, and a change that leaves version alone leaves the tag alone. The route raises version in the same update as the change it counts.

Two changes at once​

The tag a PATCH, PUT or DELETE names is compared inside a database transaction that locks the resource's row and runs the route as well, on the connection of the resource's model. Of two changes sent with the same tag, the second therefore waits for the first, finds the version the first one made and is refused with 412. The lock is SELECT … FOR UPDATE, which PostgreSQL and MySQL take on the row; SQLite takes no row lock.

The transaction commits once the route has answered. Laravel answers an exception a route throws before the middleware sees it, so a route that writes part of a change and then fails keeps what it wrote, as it would without the middleware. Such a route opens a transaction of its own around its writes.

With idempotency​

A route can take both middleware. Give it Idempotent first:

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\JsonApi\JsonApiResource;
use Illuminate\Support\Facades\Route;
use Pushery\HttpApi\Idempotency\Idempotent;
use Pushery\HttpApi\Preconditions\Conditional;

Route::patch('/orders/{order}', function (Request $request, Order $order) {
$order->update(['note' => $request->input('data.attributes.note')]);

return new JsonApiResource($order);
})->middleware(['auth:sanctum', Idempotent::class, Conditional::class]);

A retry of a change that already acted then gets the first answer back, its ETag included, because ETag is one of the headers http-api.idempotency.replayed_headers replays. In the other order, the retry reaches the comparison first and is refused with 412, because the first attempt changed the resource.