Skip to main content

FastAPI Simple Redis Cache

A simple and easy-to-use caching library for FastAPI that uses Redis as a backend.

PyPI version License: MIT

Features

  • Middleware based caching: Simple middleware extension which will add caching to your API endpoint responses.
  • Async support: Fully compatible with FastAPI's async routes.
  • Configurable expiration: Set cache TTL (Time-To-Live).
  • Lightweight: Minimal dependencies and easy to integrate.

Requirements

  • Python (>=3.13,<4.0)
  • FastAPI (>=0.116.2,<1.0.0)
  • redis-py (>=6.4.0,<7.0.0)

Installation

Install the package using your favorite package manager: PyPi Repo available here

How to Use

Available Parameters

The NaiveCache middleware allows you to set certain parameters

Necessary Parameters

Parameter Description Expected Type
redis_host URL of redis instance to connect to str
redis_port Port available to connect at redis_host str
redis_db Logical database instance at instance to connect to int

Optional Parameters

Parameter Description Expected Type
redis_username Username to use when connecting to redis instance str
redis_password Password to use when connecting to redis instance str
redis_prefix Custom prefix used for all keys before serializing (defaults to undefined-prefix) str
redis_ttl Time to live in seconds for entries in database (defaults to 300) int
excluded_paths List of strings for paths which should not have their responses cached [str]

Code Sample

First, you need to initialize the cache and register it with your FastAPI app. This is typically done in your main application file (main.py).

# main.py
import random 

from fastapi import FastAPI
from fastapi_simple_redis_cache.NaiveCache import NaiveCache

app = FastAPI()

app.add_middleware(
    NaiveCache,
    redis_host="my_redis_url",
    redis_port="my_redis_port",
    redis_db=0,
    redis_prefix="my_custom_key_prefix",
    excluded_paths=["/do-not-cache-this-path"]
)

@app.get("/")
def return_cached_value():
    """
    Will be random on first call, then cached response returned on all 
    subsequent calls
    """
    return {"message": random.choice(1,2,3,4)}

@app.get("/do-not-cache-this-path")
def return_cached_value():
    """
    Values will not be cached from this endpoint
    """
    return {"message": random.choice(1,2,3,4)}

Additional Features

Cache-Control

When sending a request to an endpoint, an additional header of cache-control:no-store can be provided which will have the middleware skip the addition of the entry to redis. This feature works regardless of the path being added to the initialized excluded_paths parameter

Response Headers

The NaiveCache middleware adds the following response headers for additional information

Header Description Expected Type
x-cache-hit Boolean indicator if the response from the API was retrieved from cache (True | False)
x-processing-time Time in float seconds that it took for the request/response to be generated float

Misc Notes

This library is a naive implementation of a caching system and is only intended as a primitive implementation for educational usage, it is not recommended to run this in production.

License

This project is licensed under the MIT License.

Metadata

Release files for fastapi-simple-redis-cache 2.0.0

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-simple-redis-cache 2.0.0
File Size Uploaded
fastapi_simple_redis_cache-2.0.0.tar.gz 4.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-simple-redis-cache 2.0.0
File Interpreter ABI Platform
fastapi_simple_redis_cache-2.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 9.0 kB

Release files / fastapi_simple_redis_cache-2.0.0.tar.gz

Download URL fastapi_simple_redis_cache-2.0.0.tar.gz
Size 4.2 kB
Tags Source
SHA-256 checksum
How to use checksums
ee54fad3c26708f386968746bb34d8a22e150f061f2ef565677802766f8c1ad0
BLAKE2b-256 checksum
How to use checksums
03e3d0d3e41640c2ced7640a729d9ed7ececb2be7eed763196f7f46729da552e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.1.4 CPython/3.11.4 Darwin/24.6.0

Release files / fastapi_simple_redis_cache-2.0.0-py3-none-any.whl

Download URL fastapi_simple_redis_cache-2.0.0-py3-none-any.whl
Size 4.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a69a65151546d708bab3d91d1c902ab0a42d60d05516bd48fce3e9ba0605f661
BLAKE2b-256 checksum
How to use checksums
0a9a3f6e7bf248287eecd84dfb4b1c6eb1488606ccd8b3797cbb05d151e8e4d8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.1.4 CPython/3.11.4 Darwin/24.6.0

Release history Release notifications | RSS feed

This release

2.0.0 This release

2 release files

1.3.3

2 release files

1.3.2

2 release files

1.3.1

2 release files

1.3.0

2 release files

1.2.3

2 release files

1.2.2

2 release files

1.2.1

2 release files

1.2.0

2 release files

1.1.1

2 release files

1.1.0

2 release files

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