Official agent skill

FastAPI-Redis SDK Development

by redis in redis/fastapi-redis-sdk

Guides development on the fastapi-redis-sdk library itself - its connection lifecycle, dependency-injected caching, and async/sync bridging.

OfficialMITAuto-check: notesBackend & APIs

Install FastAPI-Redis SDK Development

skills CLI
$ npx skills add redis/fastapi-redis-sdk --skill fastapi-redis-sdk -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install redis/fastapi-redis-sdk fastapi-redis-sdk --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/redis/fastapi-redis-sdk.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.github/skills/redis-fastapi .claude/skills/fastapi-redis-sdk && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
fastapi-redis-sdk
GitHub stars
404
Token cost
~2.5k tokens
SKILL.md length
846 words
Files
1
Skills in repo
1
Repo updated
First seen
Licence
MIT

At a glance

Guides development on the fastapi-redis-sdk library itself - its connection lifecycle, dependency-injected caching, and async/sync bridging.

  • Works in 2 steps: DI factories — cache(ttl=N,… → CacheBackend —…
  • Adding a feature or fixing a bug in fastapi-redis-sdk itself
  • SKILL.md covers Project layout, Setup and tooling, Architecture rules and Testing conventions, plus 5 more sections
  • Calls uv; needs REDIS_PASSWORD

What it does

This skill is scoped to writing code, tests or configuration for the fastapi-redis-sdk library, the official Redis integration for FastAPI, not general Redis or FastAPI questions. It lays out the project's layout, its uv and nox tooling for installing dependencies and running checks locally, and a hard architecture rule: Redis pools must be initialized through the app's lifespan, since accessing the pool without one raises a runtime error.

It covers the library's async-first design, where every dependency-injection factory is async and a sync cache backend bridges async calls for sync endpoints, plus two caching patterns built on the same connection pool: dependency-based cache, evict and put helpers with automatic HTTP caching semantics like ETag and 304 responses for GET requests only, and a lower-level backend object with get, set, delete, has and delete-group methods for conditional logic and cascading invalidation.

It also notes that the lifespan helper wraps rather than replaces an app's existing lifespan, and points to the library's own architecture docs for the details of that wrapping behavior.

When your agent uses it

  • Adding a feature or fixing a bug in fastapi-redis-sdk itself
  • Writing tests for the library's caching or lifespan behavior
  • Understanding the library's async/sync caching architecture before changing it

Example prompts

  • “Add a new cache_evict option for pattern-based key deletion.”
  • “Write a test for the sync cache backend's thread bridging behavior.”
  • “Explain how the lifespan helper wraps an existing FastAPI lifespan.”

Requirements

  • uv
  • nox

Workflow steps

2 steps, taken from the first numbered list in SKILL.md.

  1. DI factories — cache(ttl=N, eviction_group="x"), cache_evict(...),
  2. CacheBackend — get/set/delete/has/delete_group.

What it can do on your machine

Read from SKILL.md and the folder at commit ed7a579. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • uv

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md. Its commands use uv, which can reach the network depending on how they are called.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • REDIS_PASSWORD

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

FastAPI-Redis SDK Development loads about 2.5k tokens when it runs. Until then it costs about 100 tokens; SKILL.md has 846 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~100
When it runs · the whole SKILL.md, loaded when a task matches
~2.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NoteMentions a .env fileSKILL.md:175
    tings via env vars prefixed `REDIS_` or `.env` file.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from redis/fastapi-redis-sdk at commit ed7a579, republished under its MIT licence (© redis). 846 words, ~2,458 tokens.

Download SKILL.mdSave it as .claude/skills/fastapi-redis-sdk/SKILL.md (or your agent's skills folder).
name
fastapi-redis-sdk
description
fastapi-redis-sdk development skill. Use when writing code, tests, or configuration for the fastapi-redis-sdk library — the official Redis integration for FastAPI. Covers project setup (uv + nox), DI-based caching patterns, connection lifecycle, async/sync endpoints, testing conventions, and CI workflows. Do NOT use for general Redis or FastAPI questions unrelated to this library.
license
MIT

fastapi-redis-sdk

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

Project layout

src/redis_fastapi/       # Library source (single flat package)
  __init__.py            # Public API re-exports
  setup.py               # FastAPIRedis fluent builder
  lifespan.py            # redis_lifespan async context manager
  deps.py                # FastAPI DI factories & type aliases
  config.py              # RedisSettings (pydantic-settings)
  cache.py               # cache(), cache_evict(), cache_put() + middleware
  cache_backend.py       # CacheBackend (async) + SyncCacheBackend
  telemetry.py           # Optional OpenTelemetry instrumentation
  types.py               # Coder, KeyBuilder protocols
tests/
  unit/                  # fakeredis-based, no real Redis needed
  integration/           # Requires Redis on localhost:6379
pyproject.toml           # uv build backend, dependency groups, tool config
noxfile.py               # CI-mirroring sessions (lint, typecheck, security, tests, docs)

Setup and tooling

Package manager: uv. Task runner: nox (with uv venv backend).

bash
uv sync --all-groups          # Install all deps
uv run nox                    # Run ALL CI checks locally
uv run nox -s lint            # Lint + format check only
uv run nox -s typecheck       # mypy
uv run nox -s tests-3.12      # Full suite on a specific Python version
uv run nox -s tests_unit-3.12 # Unit suite only (fakeredis, no server)
uv run nox -s tests_integration-3.12  # Integration suite only (needs Redis)
uv run nox -s fix             # Auto-fix lint/format
uv run nox -s docs_serve      # Live-reload docs at localhost:8000

Architecture rules

Lifespan is mandatory

Redis pools MUST be initialised via the app lifespan. There is no fallback. Accessing the pool without a lifespan raises RuntimeError.

python
app = FastAPI()
FastAPIRedis(app).lifespan().caching()  # Always call .lifespan()
Async-first, sync via bridge
  • All DI factories (get_async_redis, get_cache_backend) are async.
  • FastAPI runs them correctly even for sync endpoints (threadpool).
  • SyncCacheBackend wraps async calls via anyio.from_thread.run — use only from sync endpoints running in FastAPI's worker threads.
Dependency injection types
python
from redis_fastapi import AsyncRedisDep, CacheBackendDep, SyncCacheBackendDep

# Async endpoint — use AsyncRedisDep or CacheBackendDep
async def endpoint(redis: AsyncRedisDep): ...
async def endpoint(cache: CacheBackendDep): ...

# Sync endpoint — use SyncCacheBackendDep
def endpoint(cache: SyncCacheBackendDep): ...
Lifespan wrapping

.lifespan() wraps the app's existing lifespan — it does not replace it. Multiple builder calls nest around whatever is already there. For explicit ordering, skip .lifespan() and compose manually with redis_lifespan:

python
from redis_fastapi import FastAPIRedis, redis_lifespan

@asynccontextmanager
async def my_lifespan(app):
    async with redis_lifespan(app):
        async with db_lifespan(app):
            yield

app = FastAPI(lifespan=my_lifespan)
FastAPIRedis(app).caching()   # no .lifespan() — user owns it

See docs/guide/architecture.md § Lifespan wrapping for details.

Caching patterns

Two patterns, same pool:

  1. DI factories — cache(ttl=N, eviction_group="x"), cache_evict(...), cache_put(...) as Depends(). Requires .caching() on setup.
    • Automatic HTTP semantics (ETag, 304, Cache-Control, X-Redis-Cache).
    • Only GET requests are cached; non-GET bypasses cache entirely.
    • Graceful degradation: Redis failures log warnings, never crash.
  2. CacheBackend — get/set/delete/has/delete_group. For conditional logic, cascade invalidation, dynamic TTL.
    • Accepts timedelta for TTL (DI factories accept int seconds only).
    • No automatic HTTP headers — add manually if needed.

Choose cache() for most GET endpoints. Choose CacheBackend when you need conditional caching, multi-step invalidation, or custom serializers. cache_evict()/cache_put() bridge writes back to the same cache keys.

Cache hit/miss internals
  • Hit: DI dependency raises CacheHitException → exception handler returns cached response. Endpoint never executes.
  • Miss: CacheResponseCaptureMiddleware buffers the response body and stores it in Redis after the endpoint returns.
  • No full ASGI middleware for reads — benchmarks showed no gain over DI. See docs/guide/architecture.md § Why not a full ASGI middleware.
Storage model

Cached entries are Redis string keys with eviction-group prefixes. Namespace deletion uses SCAN + DEL. Hash-based storage (faster eviction-group deletion via single DEL) is a future opt-in gated on Redis ≥ 8.0. See docs/guide/architecture.md § Storage model.

Telemetry

Three independent OTel layers (each opt-in):

  1. HTTP spans — opentelemetry-instrumentation-fastapi (external).
  2. Cache operation spans + metrics — FastAPIRedis(app)...otel() or REDIS_OTEL_ENABLED=true. Install fastapi-redis-sdk[otel].
  3. Redis command spans — REDIS_OTEL_REDIS_ENABLED=true or opentelemetry-instrumentation-redis (not both).

See docs/guide/architecture.md § Telemetry for span names and metrics.

Testing conventions

  • Unit tests (tests/unit/): use fakeredis.aioredis, no real Redis.
  • Integration tests (tests/integration/): real Redis, decorated with @requires_redis (auto-skip if server unreachable).
  • filterwarnings = ["error"] in pytest config — all warnings are errors.
  • Coverage threshold: 80% (--cov-fail-under=80). The integration-only session lowers this to 70 (_INTEGRATION_COV_FLOOR in noxfile.py) — 83 integration tests alone cover ~78% of src/.
  • CI runs the two suites in separate jobs: unit-tests runs tests_unit across 3 OSes x 5 Pythons, integration-tests runs tests_integration against Redis 8.8 and 7.4. See docs/guide/compatibility.md § 4.
  • asyncio_mode = "auto" — no need for @pytest.mark.asyncio.
Test fixtures
  • fake_async_redis — fakeredis instance, available in unit tests.
  • real_redis / real_async_redis — real Redis clients for integration.
  • Every integration test flushes the DB on teardown.

Configuration

All settings via env vars prefixed REDIS_ or .env file. Key vars: REDIS_URL, REDIS_HOST, REDIS_PORT, REDIS_PASSWORD, REDIS_SSL, REDIS_CLUSTER, REDIS_PREFIX, REDIS_DEFAULT_TTL.

Sentinel mode: REDIS_SENTINEL=true, REDIS_SENTINEL_NODES (comma-separated host:port), REDIS_SENTINEL_MASTER_NAME. The primary's pool is a SentinelConnectionPool in _PoolState.async_pool; _PoolState.async_sentinel holds the Sentinel clients, which the lifespan closes.

Show full SKILL.md (333 more words)Show less

Code style

  • ruff for linting + formatting (line-length 88).
  • mypy strict mode, Python 3.10 target.
  • from __future__ import annotations in all source files.
  • Type aliases use Union[] (not X | Y) for Python 3.10 compat in deps.py and types.py (ruff rule UP007 ignored there).

CI

CI is defined in .github/workflows/ci.yml and delegates to nox sessions. Do NOT add inline uv run ruff / uv run mypy commands to CI — use uv run nox -s <session> so CI and local checks stay in sync.

Do NOT change

  • Build system. The project uses uv_build as its build backend. NEVER replace it with hatchling, setuptools, flit, or any other build backend. All build config lives in pyproject.toml under [build-system] and [tool.uv.build-backend].
  • DI approach. Caching (for example) is implemented as Depends() factories (cache(), cache_evict(), cache_put()), NOT as decorators. NEVER refactor DI based solutions to use a decorator-based approach (@cache). The DI pattern is a deliberate design decision, see /guide/architecture.md for more information.
Cache key format

Default key: {prefix}:{eviction_group}:{path}:{sorted_query_params}. Eviction group is wrapped in hash-tag braces {ns} for Redis Cluster slot alignment. Query params are sorted alphabetically for determinism. Headers are NOT part of the key — use a custom key_builder for header-dependent responses (e.g. Accept).

TTL behavior

Fixed-window expiry. Accessing a cached entry does NOT extend its TTL. ttl=0 or ttl=None means no automatic expiration.

Error handling

All Redis errors (RedisError, OSError) are caught and logged as warnings. Cache reads return None/miss; writes are silently dropped. Exceptions from endpoints are never cached — only successful responses. Corrupted cache data is treated as a miss (auto-fallback).

Common pitfalls

  • anyio.from_thread.run takes a zero-arg callable returning an awaitable, NOT a coroutine object. Wrap with lambda.
  • SyncCacheBackendDep must be imported at module level when using from __future__ import annotations, or FastAPI cannot resolve the type.
  • Do not use uv add --dev in CI workflows — deps are managed by nox sessions and pyproject.toml dependency groups.
  • cache() reads get_settings() at dependency-creation time (when the module loads), not per-request. Runtime setting changes won't be picked up by already-registered routes.

© redis, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .github/skills/redis-fastapi of redis/fastapi-redis-sdk.

Open the folder on GitHubat commit ed7a579

Compare with similar skills

FastAPI-Redis SDK Development next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

FastAPI-Redis SDK Development compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
FastAPI-Redis SDK Development this skillredis/fastapi-redis-sdk404—~2.5kAutomated safety check: NotesMIT
Python Redis Module Skilljiushiwon/wg-skills110—~1.7kAutomated safety check: NotesApache-2.0
Spring Data Redisrrezartprebreza/spring-boot-skills296—~1.6kAutomated safety check: PassMIT
Backend Analysis Skilljiushiwon/wg-skills110—~1kAutomated safety check: PassApache-2.0
Funboost Faas Deployydf0509/funboost892—~956Automated safety check: PassNone
Python PatternsxenitV1/Antigravity-Workflows1307 repos~2.2kAutomated safety check: PassMIT

Similar skills

  • Python Redis Module Skill

    jiushiwon/wg-skills

    Python Redis 模块快速集成技能。面向已拥有 FastAPI 项目骨架的开发者,提供 Redis 缓存、Session 存储、分布式锁、限流、消息队列等能力的快速集成。触发词:"Python Redis"、"FastAPI Redis"、"Redis 集成"、"redis cache"、"redis session"、"redis lock"、"redis 限流"、"redis…

    110 GitHub stars~1.7k tokensUpdated 3 days ago
    DatabasesAuto-check: notes
  • Spring Data Redis

    rrezartprebreza/spring-boot-skills

    A skill your agent uses when implementing caching, session storage, rate limiting, or any Redis integration.

    296 GitHub stars~1.6k tokensUpdated 16 days ago
    Backend & APIsAuto-check passed
  • Backend Analysis Skill

    jiushiwon/wg-skills

    后端项目静态分析技能。不运行项目,直接扫描源码,为 Java(Spring Boot/Spring Cloud)、Go(Gin/Echo)、Python(FastAPI/Django/Flask)、Node.js(Express/NestJS) 项目产出 4 份报告:① 接口报告(全部 API 清单:方法/路径/入参/出参/鉴权)② 技术报告(语言/框架版本、中间件如…

    110 GitHub stars~1k tokensUpdated 3 days ago
    Backend & APIsAuto-check passed
  • Funboost Faas Deploy

    ydf0509/funboost

    当需要将 funboost 任务部署为 HTTP 微服务时使用。触发场景:通过 FastAPI/Flask/Django 暴露发布和查询接口、使用内置 FaaS router、无需手写 API 代码。关键词:FaaS, 微服务, FastAPI, Flask, Django, HTTP API, REST, fastapirouter, flaskblueprint, web deploy。

    892 GitHub stars~956 tokensUpdated 1 mo ago
    Backend & APIsAuto-check passed
  • Python Patterns

    xenitV1/Antigravity-Workflows

    Python development principles and decision-making. An agent skill from xenitV1/Antigravity-Workflows.

    130 GitHub starsUsed in 7 repos~2.2k tokens
    Backend & APIsAuto-check passed
  • Fastapi Endpoint

    davila7/claude-code-templates

    Plan and build production-ready FastAPI endpoints with async SQLAlchemy, Pydantic v2 models, dependency injection for auth, and pytest tests.

    32k GitHub stars~3.9k tokensUpdated today
    Backend & APIsAuto-check passed

Works with

Questions about FastAPI-Redis SDK Development

What does FastAPI-Redis SDK Development do?

Guides development on the fastapi-redis-sdk library itself - its connection lifecycle, dependency-injected caching, and async/sync bridging. This skill is scoped to writing code, tests or configuration for the fastapi-redis-sdk library, the official Redis integration for FastAPI, not general Redis or FastAPI questions. It lays out the project's layout, its uv and nox tooling for installing dependencies and running checks locally, and a hard architecture rule: Redis pools must be initialized through the app's lifespan, since accessing the pool without one raises a runtime error.

When should I use FastAPI-Redis SDK Development?

FastAPI-Redis SDK Development fits situations like: adding a feature or fixing a bug in fastapi-redis-sdk itself; writing tests for the library's caching or lifespan behavior; understanding the library's async/sync caching architecture before changing it.

How do I install FastAPI-Redis SDK Development in Claude Code?

Run `npx skills add redis/fastapi-redis-sdk --skill fastapi-redis-sdk -a claude-code`. Or copy the skill folder (.github/skills/redis-fastapi in redis/fastapi-redis-sdk) into .claude/skills/fastapi-redis-sdk in your project. Claude Code loads it when a task matches its description.

How do I install FastAPI-Redis SDK Development in Codex?

Run `npx skills add redis/fastapi-redis-sdk --skill fastapi-redis-sdk -a codex`. Or copy the skill folder (.github/skills/redis-fastapi in redis/fastapi-redis-sdk) into .agents/skills/fastapi-redis-sdk in your project. Codex loads it when a task matches its description.

Can I use FastAPI-Redis SDK Development in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add redis/fastapi-redis-sdk --skill fastapi-redis-sdk -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/fastapi-redis-sdk, .gemini/skills/fastapi-redis-sdk, .github/skills/fastapi-redis-sdk and .opencode/skills/fastapi-redis-sdk in your project.

What does FastAPI-Redis SDK Development need to run?

Going by SKILL.md and its folder, FastAPI-Redis SDK Development needs the command-line tools its instructions call (uv) and credentials named REDIS_PASSWORD. Our summary lists: uv; nox.

Does FastAPI-Redis SDK Development access the network?

SKILL.md contains no URLs. Its commands use uv, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is FastAPI-Redis SDK Development safe to install?

Our automated static check of SKILL.md found notes only (mentions a .env file), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does FastAPI-Redis SDK Development use?

FastAPI-Redis SDK Development is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does FastAPI-Redis SDK Development use?

About 2.5k tokens (SKILL.md is roughly 9.8k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to FastAPI-Redis SDK Development?

Skills that share tags, products or a category with FastAPI-Redis SDK Development: Python Redis Module Skill (jiushiwon/wg-skills, 110 stars), Spring Data Redis (rrezartprebreza/spring-boot-skills, 296 stars), Backend Analysis Skill (jiushiwon/wg-skills, 110 stars) and Funboost Faas Deploy (ydf0509/funboost, 892 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains FastAPI-Redis SDK Development?

redis (a GitHub organization, an official publisher) maintains it in redis/fastapi-redis-sdk, which has 404 GitHub stars. The repository was last updated on October 1, 2026.

Source: redis/fastapi-redis-sdk on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.