FastAPI Cache 2

0.2.2 · active · verified Sun Apr 12

fastapi-cache2 is a powerful and flexible library for adding caching capabilities to FastAPI applications. It supports various backend stores including Redis, Memcached, Amazon DynamoDB, and an in-memory option. It seamlessly integrates with FastAPI endpoints and general Python functions, enhancing performance by leveraging HTTP cache headers like ETag and Cache-Control. The current version is 0.2.2, and the project is actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `fastapi-cache2` with a Redis backend using FastAPI's `lifespan` event. It caches the results of two simple GET endpoints for 60 and 30 seconds respectively. Ensure a Redis server is running and accessible at `redis://localhost` or configured via the `REDIS_URL` environment variable.

import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
from redis import asyncio as aioredis

@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
    # Use os.environ.get for production readiness if Redis URL is sensitive
    redis_url = os.environ.get("REDIS_URL", "redis://localhost")
    redis = aioredis.from_url(redis_url)
    FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
    yield
    # Optional: Close redis connection if needed, though lifespan context handles it implicitly usually
    await redis.close()

app = FastAPI(lifespan=lifespan)

@app.get("/")
@cache(expire=60)
async def index():
    return {"hello": "world"}

@app.get("/items/{item_id}")
@cache(expire=30)
async def read_item(item_id: int):
    # Simulate an expensive operation
    import asyncio
    await asyncio.sleep(2)
    return {"item_id": item_id, "data": "expensive_data"}

view raw JSON →