{"id":4942,"library":"fastapi-cache2","title":"FastAPI Cache 2","description":"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.","status":"active","version":"0.2.2","language":"en","source_language":"en","source_url":"https://github.com/long2ice/fastapi-cache.git","tags":["fastapi","cache","redis","memcached","dynamodb","performance"],"install":[{"cmd":"pip install fastapi-cache2","lang":"bash","label":"Base installation"},{"cmd":"pip install \"fastapi-cache2[redis]\"","lang":"bash","label":"With Redis backend"},{"cmd":"pip install \"fastapi-cache2[memcache]\"","lang":"bash","label":"With Memcached backend"},{"cmd":"pip install \"fastapi-cache2[dynamodb]\"","lang":"bash","label":"With DynamoDB backend"}],"dependencies":[{"reason":"Core dependency for integration with FastAPI framework.","package":"fastapi"},{"reason":"For improved type hinting, particularly on Python versions below 3.10.","package":"typing-extensions","optional":false},{"reason":"Used for date and time handling.","package":"pendulum","optional":false},{"reason":"Required for using the RedisBackend cache.","package":"redis","optional":true},{"reason":"Required for using the MemcacheBackend cache.","package":"aiomcache","optional":true},{"reason":"Required for using the DynamoBackend cache.","package":"aiobotocore","optional":true}],"imports":[{"symbol":"FastAPICache","correct":"from fastapi_cache import FastAPICache"},{"symbol":"RedisBackend","correct":"from fastapi_cache.backends.redis import RedisBackend"},{"symbol":"cache","correct":"from fastapi_cache.decorator import cache"},{"note":"The `fastapi-cache` PyPI package is an older, different library. `fastapi-cache2` uses `fastapi_cache` as its top-level package name.","wrong":"from fastapi_cache.FastAPICache import FastAPICache","symbol":"FastAPICache","correct":"from fastapi_cache import FastAPICache"},{"note":"The `redis-py` library provides its async client under `redis.asyncio`.","wrong":"import aioredis","symbol":"aioredis","correct":"from redis import asyncio as aioredis"}],"quickstart":{"code":"import os\nfrom collections.abc import AsyncIterator\nfrom contextlib import asynccontextmanager\n\nfrom fastapi import FastAPI\nfrom fastapi_cache import FastAPICache\nfrom fastapi_cache.backends.redis import RedisBackend\nfrom fastapi_cache.decorator import cache\nfrom redis import asyncio as aioredis\n\n@asynccontextmanager\nasync def lifespan(_: FastAPI) -> AsyncIterator[None]:\n    # Use os.environ.get for production readiness if Redis URL is sensitive\n    redis_url = os.environ.get(\"REDIS_URL\", \"redis://localhost\")\n    redis = aioredis.from_url(redis_url)\n    FastAPICache.init(RedisBackend(redis), prefix=\"fastapi-cache\")\n    yield\n    # Optional: Close redis connection if needed, though lifespan context handles it implicitly usually\n    await redis.close()\n\napp = FastAPI(lifespan=lifespan)\n\n@app.get(\"/\")\n@cache(expire=60)\nasync def index():\n    return {\"hello\": \"world\"}\n\n@app.get(\"/items/{item_id}\")\n@cache(expire=30)\nasync def read_item(item_id: int):\n    # Simulate an expensive operation\n    import asyncio\n    await asyncio.sleep(2)\n    return {\"item_id\": item_id, \"data\": \"expensive_data\"}\n","lang":"python","description":"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."},"warnings":[{"fix":"Pin `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.","message":"The `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.","severity":"breaking","affected_versions":"0.2.2"},{"fix":"Investigate 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.","message":"Versions 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.","severity":"breaking","affected_versions":">=0.2.2"},{"fix":"Always order decorators with the route decorator first, followed by `@cache` (e.g., `@app.get('/') @cache(expire=60) async def ...`).","message":"The `@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.","severity":"gotcha","affected_versions":"All"},{"fix":"The default for `decode_responses` in `redis-py` is `False`, so avoid explicitly setting it to `True` when creating your `aioredis` client for `fastapi-cache2`.","message":"When 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.","severity":"gotcha","affected_versions":"All"},{"fix":"Add clear return type annotations to all functions decorated with `@cache` (e.g., `async def my_function() -> MyPydanticModel: ...`).","message":"For 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.","severity":"gotcha","affected_versions":"All"},{"fix":"Migrate your application's startup logic to use FastAPI's `lifespan` event context manager for initializing `FastAPICache`, as demonstrated in the quickstart.","message":"Older 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.","severity":"deprecated","affected_versions":"FastAPI >=0.95.1"}],"env_vars":null,"last_verified":"2026-04-12T00:00:00.000Z","next_check":"2026-07-11T00:00:00.000Z"}