If your collection job revisits the same resource, send a conditional GET before downloading another copy. Save the response body together with its ETag or Last-Modified value. On the next visit, a 304 Not Modified response lets your job reuse that saved body; a 200 OK response supplies a new one.
The practical catch is that a validator is useful only when you still have the corresponding content. A job that saves an ETag but loses its body cannot turn a 304 into usable records.
This tutorial is for Python developers revisiting an authorized, public JSON endpoint. It covers one resource at a time, not discovery or pagination. For those earlier decisions, see the guide to Requests, Playwright, and reliable pagination.
What each response tells your collector
An ETag is a server-provided validator. Treat its value as opaque: preserve the quotes and any W/ prefix rather than calculating a replacement from your parsed records. For GET validation, If-None-Match uses weak comparison. That makes it suitable for cache validation without promising byte-for-byte identity in every case. RFC 9110, section 13.1.2 defines these rules.
Use the ETag in If-None-Match when available. If there is no ETag but the response includes Last-Modified, send that exact value in If-Modified-Since. Do not substitute the time your job downloaded the data. If both conditions are sent, HTTP requires the recipient to ignore If-Modified-Since in favor of If-None-Match.
Your application needs three separate branches:
- 200: validate the new body, then replace the previous body and validators together.
- 304: load the previously validated body and record that it was checked again. Do not parse the 304 response as JSON; it has no response content.
- An error or unexpected response: report the failed check. Keep the last good version separate from any claim that the data is current.
A 200 response after a conditional request is not automatically a bug. The representation may have changed, or the endpoint may not honor the supplied validator. The status and the body both need checking.
Decide what counts as the same resource
The URL alone may be too broad a cache key. An English response and a French response can come from the same URL. Region, currency, account state and filters can also affect the selected representation.
The example below includes the full URL, fixed request headers and a caller-supplied context identifier in its key. Set the context identifier to describe the actual collection conditions. The label public-us does not configure a US exit; if your deployment changes region or other representation-affecting settings, change the context identifier too.
HTTP's Vary header identifies request fields involved in representation selection. The code accepts variation only on the fixed headers it stores in its identity and stops on other fields or Vary: *. This is a deliberately narrow collector, not a general HTTP cache.
It also rejects cookie-setting responses. Pages that depend on HTTP cookies need a session-aware design and separate storage boundaries. Do not reuse a public-data cache across logged-in accounts.
Save the content and validator in one file
Use Python 3.11 or newer and install Requests in your project environment:
python -m pip install requests
Save the following as conditional_get.py. It uses one JSON file per request identity, embeds the original body as base64 and verifies a SHA-256 digest before reuse. Base64 is an encoding, not encryption. Use a private directory and an appropriate retention policy for any data you are allowed to retain.
import base64
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
import requests
def checked_get(url, cache_dir, context_id="public-us", language="en-US"):
# One public, cookie-free endpoint; one writer per cache directory.
base_headers = {
"Accept": "application/json",
"Accept-Language": language,
"Accept-Encoding": "identity",
"User-Agent": "ConditionalGetExample/1.0",
}
identity = {"url": url, "context": context_id, "headers": base_headers}
key = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
directory = Path(cache_dir)
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{key}.json"
cached = None
try:
candidate = json.loads(path.read_text(encoding="utf-8"))
if candidate["identity"] == identity:
body = base64.b64decode(candidate["body"], validate=True)
if hashlib.sha256(body).hexdigest() == candidate["body_sha256"]:
json.loads(body)
cached = candidate
except (OSError, ValueError, KeyError, TypeError):
pass # Missing or damaged content means a full GET, not a conditional one.
headers = dict(base_headers)
if cached and cached.get("etag"):
headers["If-None-Match"] = cached["etag"]
elif cached and cached.get("last_modified"):
headers["If-Modified-Since"] = cached["last_modified"]
with requests.Session() as session:
# This public-data example does not use netrc or environment settings.
# Add an approved explicit proxy/CA configuration if your deployment needs one.
session.trust_env = False
with session.get(url, headers=headers, timeout=(5, 20),
allow_redirects=False) as response:
status = response.status_code
if status not in (200, 304):
response.raise_for_status()
raise RuntimeError(f"Unexpected HTTP status: {status}")
vary = response.headers.get("Vary", "")
supported = {name.lower() for name in base_headers}
if any(name.strip().lower() not in supported
for name in vary.split(",") if name.strip()):
raise RuntimeError("Unsupported Vary; review cache identity")
if response.headers.get("Set-Cookie"):
raise RuntimeError("Cookie-setting endpoint is outside this example")
now = datetime.now(timezone.utc).isoformat()
if status == 304:
if not cached or not any(k in headers for k in
("If-None-Match", "If-Modified-Since")):
raise RuntimeError("304 without a usable conditional cache entry")
entry = dict(cached)
body = base64.b64decode(entry["body"], validate=True)
for field, header in (("etag", "ETag"),
("last_modified", "Last-Modified")):
if header in response.headers:
entry[field] = response.headers[header]
else:
body = response.content
json.loads(body) # Add your actual field/record validation here.
entry = {
"identity": identity,
"body": base64.b64encode(body).decode("ascii"),
"body_sha256": hashlib.sha256(body).hexdigest(),
"etag": response.headers.get("ETag"),
"last_modified": response.headers.get("Last-Modified"),
"downloaded_at": now,
}
entry["checked_at"] = now
entry["last_status"] = status
control = response.headers.get("Cache-Control", "")
directives = {part.strip().split("=", 1)[0].lower()
for part in control.split(",")}
if "no-store" in directives:
path.unlink(missing_ok=True)
else:
temporary = path.with_suffix(".tmp")
temporary.write_text(json.dumps(entry), encoding="utf-8")
temporary.replace(path)
return {"status": status, "data": json.loads(body), "checked_at": now}
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("url")
parser.add_argument("--cache-dir", default="conditional-cache")
args = parser.parse_args()
result = checked_get(args.url, args.cache_dir)
print(json.dumps({"status": result["status"], "checked_at": result["checked_at"]}))
The fixed connect and read timeout values are teaching settings, not an end-to-end task deadline. Adjust them to your service and keep a separate job deadline where required; the proxy timeout glossary explains why naming the waiting stage matters.
The sample sets session.trust_env = False for a public, unauthenticated endpoint. It does not use environment proxy settings, netrc credentials or environment CA overrides. Deployments that require a proxy or a private CA must add an approved explicit configuration before running it. Keep certificate verification enabled. Changing the network path does not replace the cache identity or validate the returned data.
Run a repeatable check
Replace the reserved example address with an endpoint you control or are authorized to access:
python conditional_get.py 'https://your-authorized-site.example/api/items'
python conditional_get.py 'https://your-authorized-site.example/api/items'
On an endpoint that supports the chosen validator and has not changed, the first run should print status 200 and the second should print status 304. These are expected outcomes, not a transcript from that placeholder address. The command prints status and check time; application code can use the returned data value.
For a controlled acceptance check, change one record on your test server and run again. The next response should be 200 with the new value. Then remove or damage the local cache file and repeat: the script should make an unconditional GET because it no longer has content that can safely accompany a validator.
The example was exercised on November 20, 2026 with Python 3.11 and Requests 2.34.2 against a controlled local HTTP fixture. Thirteen checks passed, including initial storage, 304 reuse, changed content, damaged-cache recovery, Last-Modified fallback, language and region isolation, unsupported Vary rejection, no-store handling, and preservation of the previous body after an HTTP error or invalid JSON. This verifies those local branches; it is not a proxy-service benchmark or a test of a third-party production endpoint.
Keep “checked” separate from “downloaded”
The stored downloaded_at records when that body was obtained. checked_at records the latest successful validation. Receiving a 304 updates the latter without pretending the body was downloaded again.
If your downstream pipeline reparses saved content, record the parser version separately. A successful HTTP validation says nothing about whether a new parser can extract the required fields. The example checks JSON syntax; add your actual schema, identifier and record-level validation before replacing a production dataset.
A failed check raises an exception. It does not silently serve the old body as fresh. Your scheduler can retain the old data for a clearly marked stale view while reporting the check failure to the workflow that needs current data.
Respect storage and request limits
Cache-Control: no-cache allows storage but requires validation before reuse. no-store asks caches not to store the response. The example validates on every call and removes its local entry on a no-store response. It does not implement freshness lifetimes, shared caching or every cache extension. MDN's Cache-Control reference explains the distinction.
Conditional requests can avoid retransmitting a representation body. They still send a request and receive headers. Do not assume a 304 is free under an API quota or a proxy billing policy. Keep the existing rate budget, and handle HTTP 429 according to the responding service's guidance rather than retrying immediately.
Use one writer per cache directory for this teaching implementation. The temporary-file replacement prevents a partly written JSON file from becoming the active entry, but it is not a multi-process locking system. Redirects, authentication, streaming bodies, content-size limits and automatic retry policies need separate design before wider deployment.
Frequently asked questions
Should I send HEAD before every GET?
Not for this workflow. A conditional GET already allows the server to return headers without a representation body when validation succeeds. Adding a preliminary HEAD creates another request and does not remove the need to handle a changed GET response correctly.
What if the server provides neither ETag nor Last-Modified?
Make a normal GET and apply your own content or record comparison after downloading. A locally computed digest can detect changes in downloaded content, but it does not become a server-supported validator merely because you send it as If-None-Match.
Does a changed ETag prove my business records changed?
No. A representation can change because of metadata or formatting that your parser ignores. Validate and compare the fields relevant to your task after a 200. Conversely, do not assume a validator from one language, account or region applies to another.
Can I keep only the ETag to save local storage?
Only if you deliberately do not need the corresponding body. For this collector, retain both or discard both. When the body is missing or invalid, send an unconditional GET; a 304 cannot reconstruct content you no longer have.
About the author
小羊 writes introductory explanations and practical tips about proxy IPs, application scenarios and common usage questions.
Expertise: Proxy IP fundamentals; application scenarios; common questions; introductory guides; practical usage tips.