# httpx-cache v1.2

> Zero-config, minimal-dependency response caching and deterministic replay for `httpx` and `httpx2`.

## Install

- `pip install httpx-cache` (zero runtime dependencies; uses whichever of `httpx>=0.27,<1` or `httpx2>=2.5` is installed)
- `pip install "httpx-cache[httpx]"` / `pip install "httpx-cache[httpx2]"` / `pip install "httpx-cache[redis]"`

## Public API

- `httpx_cache.wrap(client, *, cache=None, policy="force", ttl=None, cache_post=False, cacheable_methods=None, cacheable_status_codes=None, key_fn=None, shared=False, urls_expire_after=None, stale_if_error=False, scrub_headers=(), should_cache=None, coalesce=False, max_cacheable_bytes=None, on_hit=None, on_miss=None, on_store=None)`
  Wraps an existing `httpx` or `httpx2` `Client` / `AsyncClient` (including mounts and SDK subclasses) in place and returns it.
- Per-request overrides via `request.extensions["cache"]`: `{"disabled": True, "force_refresh": True, "ttl": 30, "key": "..."}`.
- `httpx_cache.Client(...)`, `httpx_cache.AsyncClient(...)` — drop-in caching client subclasses (`httpx` if installed, else `httpx2`).
- `httpx_cache.httpx2.Client(...)`, `httpx_cache.httpx2.AsyncClient(...)` — explicit `httpx2` subclasses when both libraries are installed.
- `httpx_cache.SyncCacheTransport(transport=None, ...)` / `httpx_cache.AsyncCacheTransport(transport=None, ...)` — low-level transports supporting both `httpx` and `httpx2`.
- Stores (all string-keyed with `.get`, `.set`, `.delete`, `.keys(prefix)`, `.delete_prefix(prefix)`, `.clear`, `.stats` and async `a*` variants):
  - `SqliteCache(path=None, *, max_size_bytes=None, compress=True, busy_timeout_ms=5000)` — default WAL SQLite store (`~/.cache/httpx-cache/cache.sqlite3`, or `":memory:"`) with `.export_json()` / `.import_json()`.
  - `MemoryCache(*, max_entries=None, max_size_bytes=None)` — thread-safe in-memory LRU.
  - `JsonCache(path)` — single sorted, git-diffable JSON cassette file.
  - `FileCache(cache_dir=None, *, compress=True)` — one atomically written file per key.
  - `RedisCache(*, redis_url=None, redis=None, aredis=None, namespace="httpx_cache", default_ttl=None, compress=True)` — optional `redis>=5`.
- Policies:
  - `"force"` (default): ignores `no-store`/`private`/`no-cache`, uses `ttl`, optional `cache_post=True` body-hash keying.
  - `"rfc9111"`: honors `Cache-Control`, `Expires`, multi-variant `Vary`, permanent redirects, `ETag`/`Last-Modified` 304 revalidation.
  - `"replay"`: offline-only deterministic playback; ignores expiry and raises `CacheMissError(key, request, closest_keys=...)` on miss.
- Key helpers:
  - `httpx_cache.default_key_fn(request, *, vary_headers=())`
  - `httpx_cache.make_key_fn(*, ignore_params=(), include_headers=(), include_body=True, normalize_json_body=False, prefix="")`
- Pytest plugin (entry point `pytest11`, zero runtime dep):
  - `httpx_cache_cassette` fixture (`.wrap(client, ...)`) + `--httpx-cache-record=once|replay|rewrite` + `--httpx-cache-format=sqlite|json`
- CLI: `httpx-cache [--db PATH] stats|inspect|purge|clear|export|import`
- Metadata on every `Response`:
  - `response.extensions["from_cache"]`: `bool`
  - `response.extensions["cache_key"]`: `str`
  - `response.extensions["revalidated"]`: `True` (present when revalidated via HTTP 304)
  - `response.extensions["stale"]`: `True` (present when served via `stale_if_error`)

## Minimal Examples

### Force cache with SQLite + POST body hashing
```python
import httpx, httpx_cache

cache = httpx_cache.SqliteCache(".cache/api.sqlite3")
client = httpx_cache.wrap(httpx.Client(), cache=cache, policy="force", ttl=3600, cache_post=True)
r = client.post("https://api.example.com/v1/chat", json={"prompt": "hi"})
```

### Offline replay in tests
```python
import httpx2, httpx_cache

cache = httpx_cache.SqliteCache("tests/fixtures/cassette.sqlite3")
client = httpx_cache.wrap(httpx2.Client(), cache=cache, policy="replay")
r = client.get("https://api.example.com/items")
```

## Docs
- [README](../README.md)
- [User Guide](./guide.md)
- [Policies & RFC 9111](./cache_control.md)
- [API Reference](./api.md)
