CLAUDE.md TemplatesDeveloper Tooling

CLAUDE.md Template for FastAPI + MongoDB + Beanie ODM + Keycloak OpenID Connect Auth Engine

CLAUDE.md Template page for a FastAPI + MongoDB + Beanie ODM + Keycloak OpenID Connect Auth Engine stack. Copyable CLAUDE.md block included.

CLAUDE.md TemplateFastAPIMongoDBBeanie ODMKeycloakOpenID ConnectClaude CodeAutomationSecurityDeploymentTesting

Target User

Backend engineers building secure APIs with FastAPI and MongoDB

Use Cases

  • Scaffold FastAPI apps with Beanie ODM for MongoDB
  • Integrate Keycloak OpenID Connect for OAuth2/OIDC authentication
  • Generate CLAUDE.md templates that enforce security and production readiness

Markdown Template

CLAUDE.md Template for FastAPI + MongoDB + Beanie ODM + Keycloak OpenID Connect Auth Engine

# CLAUDE.md

Project Role: Build a FastAPI microservice backed by MongoDB using Beanie ODM, with Keycloak OpenID Connect for authentication. Provide a Claude Code instruction block that outputs a production-ready project scaffold with tests and deployment rules.

Architecture Rules:
- Use FastAPI as the HTTP layer, Beanie ODM to model MongoDB documents, and PyMongo under the hood.
- Integrate Keycloak OIDC using Authorization Code Flow with PKCE for the web app interactions.
- Tokens are validated in FastAPI using PyJWT and JWKS from Keycloak. Roles map to endpoints.
- All configuration is environment-driven (ENV vars).
- Use a clean separation: app (API), core (config and security), models (Beanie documents), db (MongoDB client), tests, and infra (deployment).

File Structure Rules:
- Do not place business logic in routes; isolate in services.
- Keep Beanie Document models under app/models.
- Keep authentication logic under app/auth.
- Use a single app instance with FastAPI lifespan for startup/shutdown.
- Tests under tests/ with pytest.

Authentication Rules:
- Use Keycloak OIDC, issuer, client_id, client_secret from env.
- Validate access_tokens with JWKS from Keycloak.
- Enforce roles via dependencies in FastAPI endpoints.
- Redirect to Keycloak login for unauthenticated requests when needed.

Database Rules:
- MongoDB connection via motor (async) and Beanie ODM.
- Use Beanie Document for User, Token, and Resource models.
- Avoid direct object IDs in API responses; return stable identifiers.

Validation Rules:
- Validate input with Pydantic models; ensure required fields; reject invalid data early.
- Use Beanie validated fields and index strategies.

Security Rules:
- Never log sensitive tokens or secrets.
- Do not expose JWKS or keys in code; fetch at runtime from Keycloak.
- Use HTTPS in all deployments; store secrets in environment vaults.
- Rotate keys via Keycloak; implement cache invalidation on JWKS rotation.

Testing Rules:
- Unit tests for pydantic validators and Beanie models.
- Integration tests for auth flow with mocked Keycloak endpoints.
- End-to-end tests for protected routes with real Keycloak sandbox in CI.

Deployment Rules:
- Use Docker and docker-compose for local dev; use a k8s manifest for prod.
- Ensure migrations are not required for Beanie; create indexes on startup.
- Collect logs via a structured logger; expose health endpoints.

Things Claude Must Not Do:
- Do not generate code that stores plaintext passwords.
- Do not assume a relational database; MongoDB only.
- Do not rely on Prisma, Mongoose, or SQL migrations.
- Do not bypass OpenID Connect validation.

Overview

The CLAUDE.md template is a copyable blueprint for building a production-grade backend using FastAPI, MongoDB, Beanie ODM, and Keycloak OpenID Connect authentication. It provides concrete, stack-specific instructions that you can paste into Claude Code to generate a working starter with security and production rules.

Direct answer: This CLAUDE.md Template accelerates building a secure FastAPI service with MongoDB (Beanie ODM) and Keycloak OIDC by giving you a ready-to-use Claude Code instruction block, an opinionated project structure, and explicit rules to follow.

When to Use This CLAUDE.md Template

  • You’re spinning up a FastAPI service that uses MongoDB as the data store and Beanie ODM to model documents.
  • You need OpenID Connect authentication managed by Keycloak and validated JWTs in FastAPI middleware.
  • You want a copyable Claude Code block to bootstrap architecture, files, tests, and deployment scripts.
  • You require a production-ready structure with security and validation rules, not a toy example.

Copyable CLAUDE.md Template

# CLAUDE.md

Project Role: Build a FastAPI microservice backed by MongoDB using Beanie ODM, with Keycloak OpenID Connect for authentication. Provide a Claude Code instruction block that outputs a production-ready project scaffold with tests and deployment rules.

Architecture Rules:
- Use FastAPI as the HTTP layer, Beanie ODM to model MongoDB documents, and PyMongo under the hood.
- Integrate Keycloak OIDC using Authorization Code Flow with PKCE for the web app interactions.
- Tokens are validated in FastAPI using PyJWT and JWKS from Keycloak. Roles map to endpoints.
- All configuration is environment-driven (ENV vars).
- Use a clean separation: app (API), core (config and security), models (Beanie documents), db (MongoDB client), tests, and infra (deployment).

File Structure Rules:
- Do not place business logic in routes; isolate in services.
- Keep Beanie Document models under app/models.
- Keep authentication logic under app/auth.
- Use a single app instance with FastAPI lifespan for startup/shutdown.
- Tests under tests/ with pytest.

Authentication Rules:
- Use Keycloak OIDC, issuer, client_id, client_secret from env.
- Validate access_tokens with JWKS from Keycloak.
- Enforce roles via dependencies in FastAPI endpoints.
- Redirect to Keycloak login for unauthenticated requests when needed.

Database Rules:
- MongoDB connection via motor (async) and Beanie ODM.
- Use Beanie Document for User, Token, and Resource models.
- Avoid direct object IDs in API responses; return stable identifiers.

Validation Rules:
- Validate input with Pydantic models; ensure required fields; reject invalid data early.
- Use Beanie validated fields and index strategies.

Security Rules:
- Never log sensitive tokens or secrets.
- Do not expose JWKS or keys in code; fetch at runtime from Keycloak.
- Use HTTPS in all deployments; store secrets in environment vaults.
- Rotate keys via Keycloak; implement cache invalidation on JWKS rotation.

Testing Rules:
- Unit tests for pydantic validators and Beanie models.
- Integration tests for auth flow with mocked Keycloak endpoints.
- End-to-end tests for protected routes with real Keycloak sandbox in CI.

Deployment Rules:
- Use Docker and docker-compose for local dev; use a k8s manifest for prod.
- Ensure migrations are not required for Beanie; create indexes on startup.
- Collect logs via a structured logger; expose health endpoints.

Things Claude Must Not Do:
- Do not generate code that stores plaintext passwords.
- Do not assume a relational database; MongoDB only.
- Do not rely on Prisma, Mongoose, or SQL migrations.
- Do not bypass OpenID Connect validation.

Recommended Project Structure

project-root/
├── app/
│   ├── main.py
│   ├── api/
│   │   └── v1/
│   │       └── endpoints/
│   ├── core/
│   │   ├── config.py
│   │   └── security.py
│   ├── models/
│   │   └── user.py
│   └── auth/
│       └── keycloak.py
├── tests/
├── infra/
│   ├── Dockerfile
│   ├── docker-compose.yml
│   └── k8s/
├── requirements.txt
└── README.md

Core Engineering Principles

  • Principle: Make security the default, not an afterthought.
  • Principle: Prefer explicit dependencies and typed data contracts (Pydantic, Beanie models).
  • Principle: Separate concerns: API, data layer, auth, and infra are distinct modules.
  • Principle: Fail fast with input validation and clear errors.
  • Principle: Environment-driven configuration and secret management.

Code Construction Rules

  • Use Beanie ODM for MongoDB; define Document models in app/models.
  • Authenticate using Keycloak OIDC; validate tokens with JWKS at runtime.
  • Endpoints should be type-annotated; use Pydantic models for request/response bodies.
  • Do not hardcode secrets; read from environment variables.
  • End-to-end tests must cover protected routes with Keycloak integration in CI.
  • Do not bypass CSRF for SPA flows; implement proper nonce handling if needed.

Security and Production Rules

  • Use HTTPS in all environments; enforce HSTS in production.
  • Validate JWT claims: issuer, audience, expiration, and scope/roles.
  • Rotate JWKS cache; refresh keys on Keycloak rotation.
  • Audit logs for authentication attempts; avoid logging tokens.
  • Limit token lifetimes and implement refresh token rotation.

Testing Checklist

  • Unit tests for models and validators.
  • Integration tests for DB interactions and auth middleware.
  • End-to-end tests around the OAuth2 authorization flow with a test Keycloak instance.
  • Static analysis and type checks in CI.

Common Mistakes to Avoid

  • Assuming a relational join model is needed for MongoDB; use Beanie to model documents instead.
  • Hardcoding Keycloak endpoints or keys in code.
  • Overexposing endpoints without proper authentication checks.

FAQ

Q: Can I adapt this CLAUDE.md Template for another OAuth provider?

A: Yes—replace Keycloak OIDC specifics with the new provider and update JWKS handling.

Q: Do I need to use Beanie ODM?

A: Beanie is used here for MongoDB; substitute with another ODM if needed and adjust queries.

Q: How do I test the Keycloak integration locally?

A: Use a local Keycloak or a test sandbox; configure env vars to point to the test realm.

Q: How to deploy securely?

A: Use Docker/Kubernetes, enable TLS, rotate keys, and monitor logs.