httpx-cache
Zero-config, minimal-dependency response caching and deterministic replay for httpx and httpx2.
Built for API clients, scrapers, AI agents, and eval/test suites — with strict RFC 9111 caching when you want it.
- Zero forced runtime dependencies: pure Python stdlib (
sqlite3,json,zlib,threading,asyncio). Bring whichever client you already use (httpx>=0.27,<1orhttpx2>=2.5), plus optional[redis](redis>=5). - Wrap any existing client:
httpx_cache.wrap(client)works onhttpx.Client,httpx.AsyncClient,httpx2.Client,httpx2.AsyncClient, and SDK subclasses (e.g., OpenAI/Anthropic HTTP clients). - Three explicit policies:
force(TTL + opt-in POST body hashing, ignoringno-store/private),replay(offline-only deterministic playback, raisesCacheMissErroron miss), andrfc9111(Cache-Control,Expires,Vary,ETag/Last-Modified304 revalidation). - Persistent SQLite by default: WAL-mode
SqliteCachewith indexed TTL expiry,zlibbody compression, LRUmax_size_bytescap,.delete(key),.clear(), and.stats().
Installation
If your project already depends on httpx or httpx2:
pip install httpx-cache
Or install with a client or Redis extra:
pip install "httpx-cache[httpx]"
pip install "httpx-cache[httpx2]"
pip install "httpx-cache[redis]"
Requires Python 3.10+ (httpx2>=2.15 requires Python 3.11+).
Quickstart
import httpx, httpx_cache
client = httpx_cache.wrap(httpx.Client(), policy="force", ttl=3600)
r1 = client.get("https://httpbin.org/get") # hits network, saved to WAL SqliteCache
r2 = client.get("https://httpbin.org/get") # served from cache
assert r1.extensions["from_cache"] is False and r2.extensions["from_cache"] is True
The exact same wrap() call works with httpx2.Client(), httpx.AsyncClient(), httpx2.AsyncClient(), and custom client subclasses.
Policies
policy="force" (default)
Ignores server Cache-Control: no-store / private / no-cache headers so APIs, scrapers, and LLM endpoints cache immediately. Opt into POST body-hash caching with cache_post=True:
import httpx2, httpx_cache
cache = httpx_cache.SqliteCache(".cache/llm.sqlite3", max_size_bytes=50 * 1024 * 1024)
client = httpx_cache.wrap(
httpx2.Client(),
cache=cache,
policy="force",
ttl=86400,
cache_post=True,
)
resp = client.post("https://api.example.com/v1/chat", json={"prompt": "hello"})
print(resp.extensions["from_cache"], resp.extensions["cache_key"])
policy="replay" (offline evals & tests)
Never opens a network connection. Serves recorded entries (even past TTL) and raises httpx_cache.CacheMissError(key, request) on any unrecorded request:
import httpx, httpx_cache
cache = httpx_cache.SqliteCache("tests/fixtures/cassette.sqlite3")
client = httpx_cache.wrap(httpx.Client(), cache=cache, policy="replay")
resp = client.post("https://api.example.com/v1/chat", json={"prompt": "hello"})
policy="rfc9111" (HTTP caching semantics)
Honors Cache-Control (no-store, no-cache, max-age, s-maxage, min-fresh, private when shared=True), Expires, Vary, permanent redirects (301/308), and conditional revalidation (ETag/If-None-Match, Last-Modified/If-Modified-Since → 304 Not Modified with response.extensions["revalidated"] = True).
with httpx_cache.Client(policy="rfc9111") as client:
r = client.get("https://api.github.com/repos/obendidi/httpx-cache")
httpx-cache vs hishel
Both libraries cache httpx requests, with different goals:
| Capability | httpx-cache v1.0 |
hishel |
|---|---|---|
| Primary focus | Pragmatic API/agent/scraper caching & deterministic offline replay | Full RFC 9111 HTTP specification compliance |
| Runtime dependencies | Zero (stdlib only; bring httpx or httpx2) |
httpx + typing-extensions / serializer deps |
httpx + httpx2 dual support |
Yes (wrap() auto-detects both, even in one process) |
httpx |
| Wrap an existing client / SDK | httpx_cache.wrap(client) in one line |
Construct transport/client explicitly |
| Default store | Persistent WAL SqliteCache (indexed TTL, LRU cap, stats) |
File / SQLite / Redis / S3 controllers |
Force-cache no-store + POST body hashing |
First-class (policy="force", cache_post=True) |
Requires custom controller/policy config |
| Offline-only fail-loud replay | First-class (policy="replay" → CacheMissError) |
Not a primary mode |
| Strict shared-proxy RFC 9111 edge cases | Core subset (policy="rfc9111") |
Best choice |
Choose hishel if you need exhaustive RFC 9111 proxy semantics. Choose httpx-cache if you want zero-dependency persistence, one-line wrapping of httpx/httpx2 SDK clients, POST/LLM caching, or offline test/eval replay.
Stores & Metadata
| Store | Persistence | Concurrency | Notes |
|---|---|---|---|
SqliteCache(path, max_size_bytes=...) |
Single WAL SQLite file (default ~/.cache/httpx-cache/cache.sqlite3) |
Thread-safe + async (asyncio.to_thread) |
Default; indexed TTL expiry, zlib compression >1 KB, .purge_expired(), .export_json() / .import_json() |
MemoryCache(max_entries=..., max_size_bytes=...) |
In-process | Thread-safe + async | O(1) LRU eviction |
JsonCache(path) |
Single sorted JSON file | Thread-safe + async | Human-readable, git-diffable cassettes for tests/evals |
FileCache(cache_dir=...) |
One file per key | Thread-safe + async | Atomic temp-file writes, zlib compression |
RedisCache(redis_url=..., namespace=...) |
Redis (pip install "httpx-cache[redis]") |
Sync + async redis>=5 |
SCAN-based .keys() / .delete_prefix() / .clear() / .stats(), TTL passthrough |
Every cache store exposes .get(key), .set(key, entry), .delete(key), .keys(prefix=""), .delete_prefix(prefix), .clear(), .stats() (CacheStats(entries, size_bytes, hits, misses, expired)) and async a* equivalents.
Every response sets:
response.extensions["from_cache"](bool)response.extensions["cache_key"](str) — pass directly tocache.delete(key)to invalidateresponse.extensions["revalidated"](True, when refreshed via304 Not Modified)response.extensions["stale"](True, when served viastale_if_error)
Production & Agent Ergonomics
client = httpx_cache.wrap(
httpx.Client(),
policy="force",
ttl=3600,
cache_post=True,
coalesce=True, # singleflight: dedupe concurrent misses
stale_if_error=True, # serve stale on 5xx / network timeout
urls_expire_after={"*/auth/*": 0, "*/prices": 30}, # per-URL TTLs (0 = never cache)
should_cache=lambda req, r: "errors" not in r.json(), # skip GraphQL 200 error payloads
scrub_headers=("set-cookie", "x-api-key"), # strip secrets before writing to disk
max_cacheable_bytes=5 * 1024 * 1024, # stream huge bodies without OOM
on_hit=lambda key, req: ..., # observability hooks (also on_miss, on_store)
)
# Per-request overrides via standard httpx extensions:
client.get("https://api.example.com/item", extensions={"cache": {"force_refresh": True}})
client.get("https://api.example.com/live", extensions={"cache": {"disabled": True}})
client.get("https://api.example.com/hot", extensions={"cache": {"ttl": 15}})
CLI Inspection
httpx-cache stats
httpx-cache inspect --prefix "POST:https://api.openai.com/"
httpx-cache purge
httpx-cache export cassette.json
httpx-cache clear --prefix "GET:https://example.com/"
Custom cache keys, make_key_fn, and streaming (stream=True) work out of the box:
client = httpx_cache.wrap(
httpx.Client(),
key_fn=httpx_cache.make_key_fn(
ignore_params=("api_key", "ts"),
include_headers=("x-tenant",),
normalize_json_body=True,
),
)
with client.stream("GET", "https://example.com/large") as r:
for chunk in r.iter_bytes():
... # cached only if the stream finishes completely
Pytest Record / Replay Fixture
Installing httpx-cache registers a lightweight pytest plugin (httpx_cache_cassette fixture + --httpx-cache-record=once|replay|rewrite):
import httpx
def test_fetch_user(httpx_cache_cassette):
with httpx_cache_cassette.wrap(httpx.Client()) as client:
resp = client.get("https://api.example.com/users/1")
assert resp.status_code == 200
Run pytest --httpx-cache-record=once locally to record into __cassettes__/, pytest --httpx-cache-record=replay in CI to fail loudly on unrecorded calls, or --httpx-cache-record=rewrite to refresh cassettes.
Explicit httpx2 Client Subclasses
When both httpx and httpx2 are installed in the same environment, httpx_cache.wrap() always matches the passed client automatically. For explicit subclasses:
import httpx_cache
import httpx_cache.httpx2 as httpx2_cache
c1 = httpx_cache.Client() # httpx.Client subclass
c2 = httpx2_cache.Client() # httpx2.Client subclass
Development
uv sync --python 3.12
uv run coverage run -m pytest && uv run coverage report
uv run ruff check .
uv run mypy httpx_cache
Metadata
Release files for httpx-cache 1.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| httpx_cache-1.2.0.tar.gz | 124.7 kB | With provenance | Details for httpx_cache-1.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| httpx_cache-1.2.0-py3-none-any.whl | Python 3 | none | any | Details for httpx_cache-1.2.0-py3-none-any.whl |
Total release size: 165.7 kB
Release files / httpx_cache-1.2.0.tar.gz
| Download URL | httpx_cache-1.2.0.tar.gz |
|---|---|
| Size | 124.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
fbe0863acacf85ac9de19a7214d9b8a4177d5ad9c26fcb7b6c7cbc169cd1cc65
|
|
BLAKE2b-256 checksum How to use checksums |
34c359f358816d3f4f5499e28f507f51438d0e463c8f16a398b08a2110654062
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / httpx_cache-1.2.0-py3-none-any.whl
| Download URL | httpx_cache-1.2.0-py3-none-any.whl |
|---|---|
| Size | 41.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ae938b6ee6b447a6a8a51d26f76dc8d0667ba5f4ccb20043671d48a3770f21ca
|
|
BLAKE2b-256 checksum How to use checksums |
328cd6d4669091fe6149473237b4e92c7aeed2248cac380b623bd7b70875cf5f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for httpx-cache 1.2.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for httpx_cache-1.2.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.