Skip to content

Repository files navigation

FastAPI-Cache X

uv Ruff Tests Coverage Status

Downloads Weekly downloads Monthly downloads

PyPI version Python Versions

English | 繁體中文

A high-performance caching extension for FastAPI: a server-side response cache with Cache-Control and ETag support, application-level caching, and optional session management.

Documentation: https://fastapi-cachex.readthedocs.io/en/latest/ — guides and the full API reference.

Features

  • HTTP caching — a @cache decorator for GET routes with Cache-Control, ETag / If-None-Match (304) and per-route invalidation.
  • Application cache — CacheManager for caching arbitrary JSON values in your own code, with compute-on-miss get_or_set() and atomic store-if-absent add().
  • Backends — in-memory, Redis and Memcached, with atomic counters, one-shot values and locks.
  • Sessions (optional) — HMAC-signed or JWT session tokens over headers, bearer tokens or cookies, with sliding expiration and IP/User-Agent binding.
  • OAuth state — one-time state tokens for CSRF protection in OAuth/OIDC flows.

Installation

uv add fastapi-cachex

Everything in the core package works with the in-memory backend. The other backends and the optional session transports ship as extras:

Extra Install Pulls in Needed for
redis uv add "fastapi-cachex[redis]" redis[hiredis], orjson AsyncRedisCacheBackend
memcached uv add "fastapi-cachex[memcached]" pymemcache MemcachedBackend (the older memcache name still works until 0.4.0)
jwt uv add "fastapi-cachex[jwt]" PyJWT SessionConfig(token_format="jwt")

Extras combine: uv add "fastapi-cachex[redis,jwt]".

Quick Start

from fastapi import FastAPI

from fastapi_cachex import AppCache, BackendProxy, cache
from fastapi_cachex.backends import MemoryBackend

app = FastAPI()
BackendProxy.set(MemoryBackend())  # or AsyncRedisCacheBackend / MemcachedBackend


@app.get("/items/{item_id}")
@cache(ttl=60)  # served from the cache for 60 seconds, with ETag revalidation
async def read_item(item_id: int):
    return {"item_id": item_id}


def build_report() -> dict:
    return {"total": 42}  # stands in for something slow


@app.get("/report")
async def report(cache: AppCache):
    # Cache any JSON value in your own code.
    return await cache.get_or_set("report", build_report, ttl=300)

Warning

The default cache key carries no user identity. Cache authenticated endpoints with private=True or a per-user key builder plus cache_authorized=True (requests with Authorization otherwise bypass the backend) — see Authenticated endpoints.

Documentation

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Releases

Used by

Contributors

Languages