CLAUDE.md TemplatesCLAUDE.md Template

FastAPI + Redis + Custom OAuth2 Password Bearer Auth + Redis-py Cache Layer — CLAUDE.md Template

CLAUDE.md Template for building a FastAPI service with Redis-backed caching and a custom OAuth2 Password Bearer authentication flow using redis-py.

CLAUDE.mdCLAUDE.md TemplateFastAPIRedisOAuth2Password Bearerredis-pyCachingSecurityClaude Code

Target User

Developers building FastAPI services with Redis-backed caching and a custom OAuth2 Password Bearer authentication layer.

Use Cases

  • API caching with Redis
  • token-based authentication
  • invalidate cache on data changes
  • session-like storage in Redis
  • scalable FastAPI services with caching

Markdown Template

FastAPI + Redis + Custom OAuth2 Password Bearer Auth + Redis-py Cache Layer — CLAUDE.md Template

# CLAUDE.md

Project role
- You are Claude Code, the coding assistant for building a FastAPI service with Redis caching and a custom OAuth2 Password Bearer authentication layer using redis-py.
- You must produce production-ready code, clear constraints, and explicit file structure.

Architecture rules
- Use FastAPI as the web framework.
- Use Redis as the primary caching layer via redis-py.
- Implement a custom OAuth2 Password Bearer token flow; tokens may be JWT-based and stored in Redis with an expiry.
- All secrets must be injected via environment variables (e.g., REDIS_URL, JWT_SECRET, TOKEN_EXPIRE_MINUTES).
- Prefer stateless API endpoints with Redis handling cache invalidation on data mutation.
- Do not rely on in-process in-memory caches for multi-instance deployments.
- Do not bypass authentication or security checks.

File structure rules
- All code lives under the app/ directory with clear module boundaries.
- Main entrypoint: app/main.py
- Auth: app/auth/ (OAuth2, token creation/validation)
- API: app/api/ (routers for resources)
- Cache: app/cache/ (Redis cache backend)
- Redis: app/redis_client.py (Redis connection helper)
- Core: app/core/ (settings, config, dependencies)
- Models/Schemas: app/models/, app/schemas/
- Tests: tests/
- Docker: Dockerfile, docker-compose.yml (for Redis integration during dev)
- Do not create irrelevant folders such as frontend/, or unrelated microservices in this CLAUDE.md block.

Authentication rules
- Implement OAuth2 with Password Bearer: endpoint /token for login, returning access_token.
- Validate user credentials against a minimal, testable store (e.g., a hashed in-memory dict during dev; swap to DB in prod).
- Store access/refresh tokens in Redis with short TTLs; refresh tokens may be optional based on design.
- Always check token expiry and revoke on logout or explicit revocation endpoint.
- Do not expose password hashes or plaintext passwords in logs or error messages.

Database/Cache rules
- Redis is the cache and token store; do not use Redis for persistent user storage.
- Configure Redis with a password and TLS in production; refer to REDIS_USE_TLS and REDIS_PASSWORD env vars.
- Cache keys must be namespaced, e.g., "cache:{route}:{params}".
- Cache invalidation: on POST/PUT/PATCH/DELETE, invalidate affected keys deterministically.

Validation rules
- Use Pydantic models for all request/response bodies.
- Validate inputs with strict constraints (min/max lengths, allowed patterns).
- Normalize and trim incoming strings; reject unknown fields if configured.

Security rules
- Serve API over HTTPS in all environments.
- Do not leak secrets; avoid printing secrets in logs.
- Use JWTs with HS256; never store raw passwords.
- Protect endpoints with dependency injection that enforces authentication on sensitive routes.

Testing rules
- Unit tests for authentication flow, Redis cache interactions, and token validation.
- Integration tests that exercise /token, protected routes, and cache eviction.
- Use HTTPX for API tests; mock Redis in unit tests and run Redis in a test container for integration tests.

Deployment rules
- Provide a Dockerfile for FastAPI app and a docker-compose.yml including Redis.
- Use environment variables for Redis URL, JWT secret, token TTL, and CORS settings.
- Ensure Redis is configured with a password and TLS in production.

Things Claude must not do
- Do not hardcode credentials; never embed secrets in CLAUDE.md blocks.
- Do not implement a non-secure token storage strategy; avoid in-memory-only sessions in multi-instance deployments.
- Do not bypass authentication checks; do not return tokens without credential verification.

Overview

A CLAUDE.md template for a production-ready FastAPI service that uses Redis as a caching layer and implements a custom OAuth2 Password Bearer authentication flow with redis-py for cache-backed tokens. This page is a copyable CLAUDE.md template page designed for Claude Code usage in a Redis-backed FastAPI stack.

Direct answer: This template provides a complete, copyable CLAUDE.md block that instructs Claude Code on how to implement FastAPI with Redis caching and a custom OAuth2 Password Bearer flow, ensuring secure token handling and cache rules.

When to Use This CLAUDE.md Template

  • You are building a FastAPI service that benefits from Redis caching for responses and tokens.
  • You need a custom OAuth2 Password Bearer flow with a Redis-backed token store.
  • You require deterministic, testable Claude Code instructions for production deployment.
  • You want a ready-to-paste CLAUDE.md that enforces security, validation, and deployment rules.

Copyable CLAUDE.md Template

# CLAUDE.md

Project role
- You are Claude Code, the coding assistant for building a FastAPI service with Redis caching and a custom OAuth2 Password Bearer authentication layer using redis-py.
- You must produce production-ready code, clear constraints, and explicit file structure.

Architecture rules
- Use FastAPI as the web framework.
- Use Redis as the primary caching layer via redis-py.
- Implement a custom OAuth2 Password Bearer token flow; tokens may be JWT-based and stored in Redis with an expiry.
- All secrets must be injected via environment variables (e.g., REDIS_URL, JWT_SECRET, TOKEN_EXPIRE_MINUTES).
- Prefer stateless API endpoints with Redis handling cache invalidation on data mutation.
- Do not rely on in-process in-memory caches for multi-instance deployments.
- Do not bypass authentication or security checks.

File structure rules
- All code lives under the app/ directory with clear module boundaries.
- Main entrypoint: app/main.py
- Auth: app/auth/ (OAuth2, token creation/validation)
- API: app/api/ (routers for resources)
- Cache: app/cache/ (Redis cache backend)
- Redis: app/redis_client.py (Redis connection helper)
- Core: app/core/ (settings, config, dependencies)
- Models/Schemas: app/models/, app/schemas/
- Tests: tests/
- Docker: Dockerfile, docker-compose.yml (for Redis integration during dev)
- Do not create irrelevant folders such as frontend/, or unrelated microservices in this CLAUDE.md block.

Authentication rules
- Implement OAuth2 with Password Bearer: endpoint /token for login, returning access_token.
- Validate user credentials against a minimal, testable store (e.g., a hashed in-memory dict during dev; swap to DB in prod).
- Store access/refresh tokens in Redis with short TTLs; refresh tokens may be optional based on design.
- Always check token expiry and revoke on logout or explicit revocation endpoint.
- Do not expose password hashes or plaintext passwords in logs or error messages.

Database/Cache rules
- Redis is the cache and token store; do not use Redis for persistent user storage.
- Configure Redis with a password and TLS in production; refer to REDIS_USE_TLS and REDIS_PASSWORD env vars.
- Cache keys must be namespaced, e.g., "cache:{route}:{params}".
- Cache invalidation: on POST/PUT/PATCH/DELETE, invalidate affected keys deterministically.

Validation rules
- Use Pydantic models for all request/response bodies.
- Validate inputs with strict constraints (min/max lengths, allowed patterns).
- Normalize and trim incoming strings; reject unknown fields if configured.

Security rules
- Serve API over HTTPS in all environments.
- Do not leak secrets; avoid printing secrets in logs.
- Use JWTs with HS256; never store raw passwords.
- Protect endpoints with dependency injection that enforces authentication on sensitive routes.

Testing rules
- Unit tests for authentication flow, Redis cache interactions, and token validation.
- Integration tests that exercise /token, protected routes, and cache eviction.
- Use HTTPX for API tests; mock Redis in unit tests and run Redis in a test container for integration tests.

Deployment rules
- Provide a Dockerfile for FastAPI app and a docker-compose.yml including Redis.
- Use environment variables for Redis URL, JWT secret, token TTL, and CORS settings.
- Ensure Redis is configured with a password and TLS in production.

Things Claude must not do
- Do not hardcode credentials; never embed secrets in CLAUDE.md blocks.
- Do not implement a non-secure token storage strategy; avoid in-memory-only sessions in multi-instance deployments.
- Do not bypass authentication checks; do not return tokens without credential verification.

Recommended Project Structure

app/
├── main.py
├── config.py
├── auth/
│   ├── oauth2.py
│   └── token.py
├── api/
│   └── v1/
│       └── endpoints/
├── core/
│   ├── config.py
│   └── security.py
├── models/
│   └── user.py
├── schemas/
│   └── user.py
├── services/
│   └── user_service.py
├── cache/
│   └── cache_backend.py
├── redis_client.py
└── tests/
    └── test_auth.py

Core Engineering Principles

  • Explicit dependencies: lock versions and pin to known-compatible ranges.
  • Idempotent endpoints: GET/PUT/DELETE should be safe to retry without side effects.
  • Clear separation of concerns: auth, cache, API routes, and data models are isolated.
  • Deterministic caching: cache keys are stable, namespaced, and invalidated on mutations.
  • Fail-fast and observable: meaningful errors, structured logs, and metrics hooks.

Code Construction Rules

  • Use FastAPI dependency injection to enforce authentication on protected routes.
  • Implement Redis cache layer in app/cache/ with a simple interface: get, set, delete, and invalidate.
  • Credentials validation should be deterministic and testable; avoid external flaky dependencies in unit tests.
  • Token generation should be deterministic and signed; store a reference in Redis to enable token revocation if needed.
  • Do not bypass TLS or secret management; use environment variables for secrets.

Security and Production Rules

  • Enable TLS in all production deployments; terminate TLS at the edge if using a reverse proxy.
  • Protect the /token endpoint with rate limiting and strong credential checks.
  • Store Redis credentials securely (ENV) and enable Redis ACLs where possible.
  • Do not log secrets; scrub sensitive fields from logs.
  • Use short-lived access tokens with Redis-backed revocation capabilities.

Testing Checklist

  • Unit tests for token generation, password validation, and cache operations.
  • Integration tests for /token flow, protected endpoints, and Redis cache interactions.
  • End-to-end tests with Redis container to verify caching behavior and eviction rules.
  • Static analysis and type checks (mypy/pytest) as part of CI.

Common Mistakes to Avoid

  • Forgetting to invalidate cache after mutations leading to stale data.
  • Storing secrets in code or logs; always use environment variables.
  • Assuming in-process memory cache suffices for multi-instance deployments.
  • Weak token handling or insecure token storage in Redis.

FAQ

What is the primary use case of this CLAUDE.md Template?
Provide a copyable CLAUDE.md block for building a FastAPI service with Redis caching and a custom OAuth2 Password Bearer flow using redis-py.
Which stack does this template target?
FastAPI, Redis as a cache layer, a custom OAuth2 Password Bearer authentication flow, and Redis-py for cache operations.
How should tokens be stored and invalidated?
Store short-lived access tokens in Redis with a revocation strategy; avoid long-lived tokens without revocation. Validate tokens on each protected request.
Where should secrets live?
In environment variables; never in code or logs. Use a secret manager in production.
What is required for deployment?
Dockerfile for the FastAPI app and docker-compose.yml to run Redis, with TLS and password protection enabled in production.