Skip to main content

The official Redis integration with FastAPI

Project description

Official FastAPI integration for Redis

Idiomatic Redis integration for FastAPI - connection management and DI-based caching with automatic key consistency.

Integration PyPI - Version Python Version MIT licensed Checked with mypy Ruff codecov Guide

Discord Twitch YouTube Twitter Stack Exchange questions

Features

  • Fluent setupFastAPIRedis(app).lifespan().caching() configures pools and caching in one chain, attaching to the FastAPI lifespan events
  • Dependency injectioncache(), cache_evict(), cache_put() as Depends() factories, plus CacheBackend for complex invalidation and conditional logic
  • HTTP-native cachingETag, 304 Not Modified, Cache-Control directives out of the box
  • Testable — full dependency_overrides support; no need for monkey-patching
  • Pydantic-validated configuration — fully configurable via environment variables or via an .env file

Requirements

Dependency Supported versions
Python 3.10 to 3.14
FastAPI 0.115+
redis-py 6.0+
Pydantic 2.0+
Redis server 7.4+

Installation

pip install fastapi-redis-sdk

Quick Start

from fastapi import FastAPI
from redis_fastapi import FastAPIRedis, RedisDep, AsyncRedisDep

app = FastAPI()
FastAPIRedis(app).lifespan()

@app.get("/items")
def get_items(redis: RedisDep):
    return {"items": redis.get("items")}

@app.get("/async-items")
async def get_items_async(redis: AsyncRedisDep):
    return {"items": await redis.get("items")}

Connection pools are managed automatically and closed on shutdown. The builder wraps any existing lifespan - multiple libraries can each register their own without conflicting. See Configuration for connection options.

Caching

Two caching patterns for different needs, sharing the same connection pool:

Pattern Best for
cache(), cache_evict(), cache_put() Most endpoints - read/write/invalidate
CacheBackend Complex invalidation, conditional logic

DI factories - read, invalidate, write-through

from fastapi import Depends
from redis_fastapi import FastAPIRedis, cache, cache_evict, cache_put, default_key_builder

app = FastAPI()
FastAPIRedis(app).lifespan().caching()


# READ - cache GET responses
@app.get("/products/{product_id}", dependencies=[Depends(cache(ttl=300, eviction_group="products"))])
async def get_product(product_id: int):
    return await db.get_product(product_id)


# INVALIDATE - evict the cached entry on delete
@app.delete(
    "/products/{product_id}",
    dependencies=[Depends(cache_evict(eviction_group="products", key_builder=default_key_builder))],
)
async def delete_product(product_id: int):
    await db.delete(product_id)


# WRITE-THROUGH - update the cache so the next GET is a HIT
@app.put(
    "/products/{product_id}",
    dependencies=[Depends(cache_put(eviction_group="products", key_builder=default_key_builder, ttl=300))],
)
async def replace_product(product_id: int, body: Product):
    return await db.update(product_id, body)

All three factories share the same key_builder, so GET, DELETE, and PUT on the same path target the exact same cache key. Responses include X-Redis-Cache (HIT/MISS), Cache-Control, and ETag headers with 304 Not Modified support. Full dependency_overrides support makes testing straightforward - no monkey-patching required.

CacheBackend - full control via dependency injection

from redis_fastapi import CacheBackendDep

@app.get("/dashboard/{user_id}")
async def dashboard(user_id: int, cache: CacheBackendDep):
    cached = await cache.get(f"stats:{user_id}", eviction_group="dashboard")
    if cached:
        return cached
    result = await compute_dashboard(user_id)
    await cache.set(f"stats:{user_id}", result, ttl=300, eviction_group="dashboard")
    return result

Provides get/set/delete/has/delete_group with automatic JSON serialization. Use it for conditional caching, cascade invalidation, dynamic TTL, and intermediate result caching.

See the Caching Guide for detailed examples, feature comparison, and best practices.

Configuration

All settings are read from environment variables (prefixed REDIS_) or a .env file. Set REDIS_URL for the simplest setup:

export REDIS_URL=redis://user:pass@host:6379/0

Or configure individual fields:

export REDIS_HOST=redis.example.com
export REDIS_PORT=6380
export REDIS_PASSWORD=secret

Additional options: TLS (REDIS_SSL, REDIS_SSL_CERTFILE, etc.), connection pool (REDIS_MAX_CONNECTIONS, REDIS_SOCKET_TIMEOUT), OSS Cluster mode (REDIS_CLUSTER=true), key prefix (REDIS_PREFIX), and default cache TTL (REDIS_DEFAULT_TTL, default 0 = no expiry).

For programmatic configuration:

from redis_fastapi import get_settings

settings = get_settings()
settings.url = "redis://custom:6379/0"
settings.default_ttl = 120

See the Configuration Guide for the full environment variable reference and API details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_redis_sdk-0.7.0.tar.gz (23.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_redis_sdk-0.7.0-py3-none-any.whl (26.7 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_redis_sdk-0.7.0.tar.gz.

File metadata

  • Download URL: fastapi_redis_sdk-0.7.0.tar.gz
  • Upload date:
  • Size: 23.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for fastapi_redis_sdk-0.7.0.tar.gz
Algorithm Hash digest
SHA256 01bd948430dc97a1f4a3674fcbbf8316ce8856d1ee4dbc1fe669c7decca98084
MD5 3beb12833bf6f73b8cae9367c2c0d9dc
BLAKE2b-256 903522064b1b7a3160a64e17498b823af3cae86f4e35c20274e719367861ccef

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_redis_sdk-0.7.0.tar.gz:

Publisher: release.yml on redis/fastapi-redis-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastapi_redis_sdk-0.7.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_redis_sdk-0.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 07a685664900ddb72882d351ebc6b712d4aa9ba42b131e2010f47cc48785f4a1
MD5 14f06e83b8d45a786ef227b60b738987
BLAKE2b-256 3b242c8c44ed7822090378295e03f9bd05f56c330ac29c847b4d38ea8be1c30e

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_redis_sdk-0.7.0-py3-none-any.whl:

Publisher: release.yml on redis/fastapi-redis-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page