Install & Compatibility
Where this runs
tested against v0.2.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.265s · 78.6MB
glibcpy 3.10–3.920 runs
installs and imports cleanly · install 5.8s · import 0.246s · 79MB
79MB installed
● package 79MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
FastAPICache
✓ from fastapi_cache import FastAPICache
✗ from fastapi_cache import FastAPICache
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"}
Debug
Known issues
breakingThe `fastapi-cache2` library, specifically version 0.2.2, has a strict dependency requirement on `redis-py` version `4.6.0`. Upgrading `redis-py` to version `5.x` or higher in your project will cause `fastapi-cache2` to break.fixPin `redis-py` to `==4.6.0` in your project's dependencies if using `fastapi-cache2==0.2.2`. Check the `fastapi-cache2` changelog for future compatibility with `redis-py` 5.x.
affects: 0.2.2
breakingVersions of `fastapi-cache2` 0.2.2 and later can conflict with libraries like `fastapi-pagination` that also rely heavily on FastAPI's dependency injection. This may lead to `UninitializedConfigurationError` when both libraries are used on the same endpoint.fixInvestigate alternative caching strategies for paginated endpoints or consult the `fastapi-cache` GitHub issues for potential workarounds or future compatibility updates. It indicates a conflict in how `fastapi-cache2` wraps routes and handles dependencies.
affects: >=0.2.2
gotchaThe `@cache` decorator must be placed *after* the FastAPI route decorator (e.g., `@app.get('/')`) to function correctly. Incorrect placement can lead to caching not working as expected or runtime errors.fixAlways order decorators with the route decorator first, followed by `@cache` (e.g., `@app.get('/') @cache(expire=60) async def ...`). affects: All
gotchaWhen initializing `RedisBackend`, ensure that the `redis-py` client instance passed to it does *not* have `decode_responses=True` set. Cached data is stored as bytes, and decoding them prematurely by the client will corrupt the cache data.fixThe default for `decode_responses` in `redis-py` is `False`, so avoid explicitly setting it to `True` when creating your `aioredis` client for `fastapi-cache2`.
affects: All
gotchaFor functions decorated with `@cache` using the default `JsonCoder`, it is highly recommended to provide explicit return type annotations. Without them, especially for Pydantic models or custom dataclasses, the cache might store primitive JSON types instead of the fully structured object, potentially leading to unexpected data shapes on cache hits.fixAdd clear return type annotations to all functions decorated with `@cache` (e.g., `async def my_function() -> MyPydanticModel: ...`).
affects: All
deprecatedOlder examples might show `FastAPICache.init()` being called within `app.on_event("startup")`. While still functional on older FastAPI versions, `app.on_event` is deprecated in FastAPI versions 0.95.1 and newer.fixMigrate your application's startup logic to use FastAPI's `lifespan` event context manager for initializing `FastAPICache`, as demonstrated in the quickstart.
affects: FastAPI >=0.95.1
Upgrade
Version history
0.2.2latest on PyPI · released Jul 24, 2024
Audit
Dependencies
fastapirequiredCore dependency for integration with FastAPI framework.
typing-extensionsrequiredFor improved type hinting, particularly on Python versions below 3.10.
pendulumrequiredUsed for date and time handling.
redisoptionalRequired for using the RedisBackend cache.
aiomcacheoptionalRequired for using the MemcacheBackend cache.
aiobotocoreoptionalRequired for using the DynamoBackend cache.