Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

fastapi-cache-stable

Community-maintained stable fork of fastapi-cache2. This is an alpha (0.3.0a1) based on v0.2.2. It is experimental and not recommended for production. The fastapi_cache import and public API are unchanged. See COMPATIBILITY.md, MIGRATION.md, SUPPORT.md, SECURITY.md and FORK_ORIGIN.md. Not affiliated with the original author.

Implemented in this alpha: error responses are not cached, opt-in TypedJsonCoder for Pydantic v2, and the clear() fixes. Auth/privacy, ETag, InMemory expiry/isolation, non-JSON bypass and _spec_type fixes are targeted for later 0.3.0 pre-releases; see MIGRATION.md.

Branch model: stable is the only maintained and release branch. main mirrors the upstream project and is not a second development branch.

pypi license CI

Introduction

fastapi-cache is a tool to cache FastAPI endpoint and function results, with backends supporting Redis, Memcached, and Amazon DynamoDB.

Features

  • Supports redis, memcache, dynamodb, and in-memory backends.
  • Easy integration with FastAPI.
  • Inherited ETag and Cache-Control support, including conditional If-None-Match requests. Correctness fixes for these headers are targeted for later 0.3.0 pre-releases.

Alpha caveat: ETag/Cache-Control correctness, auth/privacy defaults and InMemory expiration/isolation are not fixed in 0.3.0a1. See COMPATIBILITY.md.

Requirements

  • FastAPI
  • redis when using RedisBackend.
  • memcache when using MemcacheBackend.
  • aiobotocore when using DynamoBackend.

Install

> pip install fastapi-cache-stable

or

> pip install "fastapi-cache-stable[redis]"

or

> pip install "fastapi-cache-stable[memcache]"

or

> pip install "fastapi-cache-stable[dynamodb]"

Usage

Quick Start

from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response

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]:
    redis = aioredis.from_url("redis://localhost")
    FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
    yield


app = FastAPI(lifespan=lifespan)


@cache()
async def get_cache():
    return 1


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

Initialization

First you must call FastAPICache.init during startup FastAPI startup; this is where you set global configuration.

Use the @cache decorator

If you want cache a FastAPI response transparently, you can use the @cache decorator between the router decorator and the view function.

Parameter type default description
expire int sets the caching time in seconds
namespace str "" namespace to use to store certain cache items
coder Coder JsonCoder which coder to use, e.g. JsonCoder
key_builder KeyBuilder callable default_key_builder which key builder to use
injected_dependency_namespace str __fastapi_cache prefix for injected dependency keywords.
cache_status_header str X-FastAPI-Cache Name for the header on the response indicating if the request was served from cache; either HIT or MISS.

You can also use the @cache decorator on regular functions to cache their result.

Injected Request and Response dependencies

The cache decorator injects dependencies for the Request and Response objects, so that it can add cache control headers to the outgoing response, and return a 304 Not Modified response when the incoming request has a matching If-Non-Match header. This only happens if the decorated endpoint doesn't already list these dependencies already.

The keyword arguments for these extra dependencies are named __fastapi_cache_request and __fastapi_cache_response to minimize collisions. Use the injected_dependency_namespace argument to @cache to change the prefix used if those names would clash anyway.

Supported data types

The default JsonCoder stores any data type that FastAPI can convert to JSON, including Pydantic models and dataclasses. On a cache hit it returns the decoded JSON value (plain dicts/lists), not the annotated model; this is the legacy fastapi-cache2 behavior.

Pydantic v2 users can opt into typed restoration with TypedJsonCoder:

from fastapi_cache import FastAPICache
from fastapi_cache.coder import TypedJsonCoder

FastAPICache.init(backend, coder=TypedJsonCoder)

or per endpoint:

from .models import SomeModel, create_some_model

@app.get("/foo")
@cache(expire=60, coder=TypedJsonCoder)
async def foo() -> SomeModel:
    return create_some_model()

TypedJsonCoder uses the endpoint return annotation to restore the annotated type and propagates validation errors. It requires Pydantic v2; Pydantic v1 and annotations that cannot be represented by a Pydantic v2 schema keep the legacy decoded behavior.

For broader type support, use fastapi_cache.coder.PickleCoder or implement a custom coder (see below).

Custom coder

By default use JsonCoder, you can write custom coder to encode and decode cache result, just need inherit fastapi_cache.coder.Coder.

from typing import Any
import orjson
from fastapi.encoders import jsonable_encoder
from fastapi_cache import Coder

class ORJsonCoder(Coder):
    @classmethod
    def encode(cls, value: Any) -> bytes:
        return orjson.dumps(
            value,
            default=jsonable_encoder,
            option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY,
        )

    @classmethod
    def decode(cls, value: bytes) -> Any:
        return orjson.loads(value)


@app.get("/")
@cache(expire=60, coder=ORJsonCoder)
async def index():
    return dict(hello="world")

Custom key builder

By default the default_key_builder builtin key builder is used; this creates a cache key from the function module and name, and the positional and keyword arguments converted to their repr() representations, encoded as a MD5 hash. You can provide your own by passing a key builder in to @cache(), or to FastAPICache.init() to apply globally.

For example, if you wanted to use the request method, URL and query string as a cache key instead of the function identifier you could use:

def request_key_builder(
    func,
    namespace: str = "",
    *,
    request: Request = None,
    response: Response = None,
    *args,
    **kwargs,
):
    return ":".join([
        namespace,
        request.method.lower(),
        request.url.path,
        repr(sorted(request.query_params.items()))
    ])


@app.get("/")
@cache(expire=60, key_builder=request_key_builder)
async def index():
    return dict(hello="world")

Backend notes

InMemoryBackend

The InMemoryBackend stores cache data in memory and only deletes when an expired key is accessed. This means that if you don't access a function after data has been cached, the data will not be removed automatically.

RedisBackend

When using the Redis backend, please make sure you pass in a redis client that does not decode responses (decode_responses must be False, which is the default). Cached data is stored as bytes (binary), decoding these in the Redis client would break caching.

Tests and coverage

coverage run -m pytest
coverage html
xdg-open htmlcov/index.html

License

This project is licensed under the Apache-2.0 License.

Metadata

Release files for fastapi-cache-stable 0.3.0a1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-cache-stable 0.3.0a1
File Size Uploaded Provenance Actions
fastapi_cache_stable-0.3.0a1.tar.gz 28.5 kB With provenance Details for fastapi_cache_stable-0.3.0a1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-cache-stable 0.3.0a1
File Interpreter ABI Platform Actions
fastapi_cache_stable-0.3.0a1-py3-none-any.whl Python 3 none any Details for fastapi_cache_stable-0.3.0a1-py3-none-any.whl

Total release size: 48.7 kB

Release files / fastapi_cache_stable-0.3.0a1.tar.gz

Download URL fastapi_cache_stable-0.3.0a1.tar.gz
Size 28.5 kB
Tags Source
SHA-256 checksum
How to use checksums
18763d4b05c03bef07f3d1e116a33092b81598d26c53027a4cc84a026a4c9347
BLAKE2b-256 checksum
How to use checksums
a1ee48072c6914fe2c527cba83093707d8e847b54bc1d4e2dede5d529ab2d973
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.

Transparency log

Release files / fastapi_cache_stable-0.3.0a1-py3-none-any.whl

Download URL fastapi_cache_stable-0.3.0a1-py3-none-any.whl
Size 20.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
932ebb37c9e97030f196b46081cd09d64e24f6162110de0bfe75549740ab937c
BLAKE2b-256 checksum
How to use checksums
8a4de2b7842def2a782be0846cec91e98f378f5a381d3dd697e36fe8fec90b03
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.

Transparency log

Security for fastapi-cache-stable 0.3.0a1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fastapi_cache_stable-0.3.0a1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 14, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page