liveBook · Manning

Conditional request

As explained in The Design of Web APIs, Second Edition

A conditional request is an HTTP request whose response depends on whether a specified resource condition, such as modification since a prior retrieval, is satisfied.

A conditional request asks an HTTP API to act only when a resource condition holds. It prevents stale updates and avoids downloading unchanged data. section 12.5.4 section 13.4.1

Use the condition that matches the operation:

  • For updates, return an ETag when reading a resource, then send it in If-Match. Reject a stale version with 412 Precondition Failed; the consumer rereads the resource before retrying. section 12.5.4
  • For cached reads, send the previous ETag in If-None-Match. Return 304 Not Modified without data when unchanged, or 200 OK with updated data and a new ETag when modified. section 13.4.5
  • Alternatively, use Last-Modified with If-Unmodified-Since for updates, or a date-based conditional read as supported by HTTP. section 12.5.4 section 13.4.5

Banking application cache

A banking app caches account 123 for ten minutes, but the balance may become inaccurate during that interval. Before displaying the cached balance, it sends a conditional read with the cached ETag. An unchanged account produces 304 and preserves the cache; a changed account produces fresh data and a replacement ETag. section 13.4.1 section 13.4.5

Figure 12.5 By returning the resource data version in an Etag header on reading, we can condition updates with the If-Match header and ensure that data stays uncorrupted.
figure

Trace the read-ETag, update-If-Match, and stale-version rejection flow that protects updates from reverting newer data. section 12.5.4

Figure 13.8 The If-None-Match header allows us to return data only if it has changed compared to the provided Etag value.
figure

Trace how If-None-Match distinguishes an unchanged cached representation from a modified one. section 13.4.5

How The Design of Web APIs, Second Edition covers it

How deep it goes
Explains ETag, date validators, request headers, success and failure responses, and OpenAPI documentation requirements.
Examples
Uses owner updates, cached banking account data, and downloadable account statements as concrete scenarios.
What it assumes
Assumes familiarity with HTTP requests, responses, resource reads, updates, caching, and OpenAPI documentation.
What you can do after
Apply it via HTTP headers to protect PUT or PATCH updates and refresh cached data only when necessary.
How it connects
Connects HTTP caching, ETag, Last-Modified, PUT, PATCH, OpenAPI, and 304 Not Modified.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Design of Web APIs, Second Edition. The section links point to the parts of the book it draws on.