CLAUDE.md Template: FastAPI + PostgreSQL + OAuth2 JWT + SQLAlchemy 2.0 Async
CLAUDE.md Template for FastAPI + PostgreSQL + OAuth2 JWT with SQLAlchemy 2.0 Async.
Target User
Developers needing a CLAUDE.md Template for FastAPI + PostgreSQL + OAuth2 JWT with async SQLAlchemy
Use Cases
- Bootstrapping production-grade FastAPI apps
- Standardized auth pipeline with JWT
- Async ORM data access
- PostgreSQL-backed persistence
- Migrations and testing ready
- Consistent CLAUDE Code templates
Markdown Template
CLAUDE.md Template: FastAPI + PostgreSQL + OAuth2 JWT + SQLAlchemy 2.0 Async
# CLAUDE.md
Project role: You are Claude Code. Your job is to output a complete, production-ready FastAPI + PostgreSQL + OAuth2 JWT stack using SQLAlchemy 2.0 Async ORM. All code blocks you generate must be ready to paste into a repository and run with sensible defaults.
Architecture rules:
- Build an API-first application with clear separation of concerns (api, core, db, models, schemas, services, repositories).
- Use Async SQLAlchemy 2.0 with PostgreSQL (async_session).
- Authentication uses OAuth2PasswordBearer with JWT access tokens. Tokens signed with HS256 and a 15-minute expiry.
- Use Alembic for migrations and environment-based config.
File structure rules:
- Do not output irrelevant folders. Only include a practical structure below.
- Ensure all imports are explicit and type-annotated.
Authentication rules:
- Passwords hashed with bcrypt (passlib).
- OAuth2 token endpoint issues access tokens and refresh tokens with short lifetimes.
- Validate user existence, correct password, and active user status.
- Do not reveal sensitive user info in error messages.
Database rules:
- PostgreSQL as the primary DB. Use SQLAlchemy ORM models; do not use raw string SQL where possible.
- Use environment variables for DB connection (DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME).
- Use migrations via Alembic.
Validation rules:
- Use Pydantic models for request/response validation and serialization.
- Validate IDs as UUIDs where appropriate; otherwise, integers are fine for internal IDs.
Security rules:
- Do not leak stack traces to clients.
- Return appropriate HTTP status codes for auth failures (401/403) and validation errors (422).
- Ensure token signing key is loaded from environment variable (JWT_SECRET) and rotation is easy via config.
- Do not log sensitive credentials; mask token payloads in logs.
- Use TLS/HTTPS in production; configure CORS to limit origins.
- Use Alembic for migrations; never alter schema at runtime without migrations.
Testing rules:
- Provide unit tests for utilities, password hashing, and token creation.
- Provide integration tests for the /auth/token and protected endpoints using a test database.
- Use pytest with async support; fixtures for DB setup/teardown.
Deployment rules:
- Include docker-compose with a Postgres service and the FastAPI app.
- Provide a simple, reproducible startup command.
- Ensure ENV vars can override defaults.
Things Claude must not do:
- Do not output synchronous DB calls; do not rely on in-memory SQLite for production.
- Do not generate code that bypasses authentication.
- Do not mix ORM versions; do not bypass typing or violate Pydantic models.Overview
CLAUDE.md template is a copyable blueprint that enables Claude Code to generate a production-ready FastAPI + PostgreSQL authentication pipeline using OAuth2 with JWT and SQLAlchemy 2.0 Async ORM. It specifies roles, rules, and constraints so the resulting codebase is deterministic and testable.
Direct answer: Use this CLAUDE.md Template to produce a FastAPI app with async SQLAlchemy, PostgreSQL, and OAuth2 JWT authentication, wired for production-grade security and testing.
When to Use This CLAUDE.md Template
- When you need a complete, reproducible FastAPI + PostgreSQL stack with OAuth2 JWT authentication.
- When using SQLAlchemy 2.0 Async ORM for async DB operations.
- When you want a clean project structure and ready-to-run tests and migrations.
- When you require a CLAUDE.md template that can be pasted into Claude Code to generate code consistently.
Copyable CLAUDE.md Template
# CLAUDE.md
Project role: You are Claude Code. Your job is to output a complete, production-ready FastAPI + PostgreSQL + OAuth2 JWT stack using SQLAlchemy 2.0 Async ORM. All code blocks you generate must be ready to paste into a repository and run with sensible defaults.
Architecture rules:
- Build an API-first application with clear separation of concerns (api, core, db, models, schemas, services, repositories).
- Use Async SQLAlchemy 2.0 with PostgreSQL (async_session).
- Authentication uses OAuth2PasswordBearer with JWT access tokens. Tokens signed with HS256 and a 15-minute expiry.
- Use Alembic for migrations and environment-based config.
File structure rules:
- Do not output irrelevant folders. Only include a practical structure below.
- Ensure all imports are explicit and type-annotated.
Authentication rules:
- Passwords hashed with bcrypt (passlib).
- OAuth2 token endpoint issues access tokens and refresh tokens with short lifetimes.
- Validate user existence, correct password, and active user status.
- Do not reveal sensitive user info in error messages.
Database rules:
- PostgreSQL as the primary DB. Use SQLAlchemy ORM models; do not use raw string SQL where possible.
- Use environment variables for DB connection (DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME).
- Use migrations via Alembic.
Validation rules:
- Use Pydantic models for request/response validation and serialization.
- Validate IDs as UUIDs where appropriate; otherwise, integers are fine for internal IDs.
Security rules:
- Do not leak stack traces to clients.
- Return appropriate HTTP status codes for auth failures (401/403) and validation errors (422).
- Ensure token signing key is loaded from environment variable (JWT_SECRET) and rotation is easy via config.
- Do not log sensitive credentials; mask token payloads in logs.
- Use TLS/HTTPS in production; configure CORS to limit origins.
- Use Alembic for migrations; never alter schema at runtime without migrations.
Testing rules:
- Provide unit tests for utilities, password hashing, and token creation.
- Provide integration tests for the /auth/token and protected endpoints using a test database.
- Use pytest with async support; fixtures for DB setup/teardown.
Deployment rules:
- Include docker-compose with a Postgres service and the FastAPI app.
- Provide a simple, reproducible startup command.
- Ensure ENV vars can override defaults.
Things Claude must not do:
- Do not output synchronous DB calls; do not rely on in-memory SQLite for production.
- Do not generate code that bypasses authentication.
- Do not mix ORM versions; do not bypass typing or violate Pydantic models.
Recommended Project Structure
fastapi-postgresql-oauth2-sqlalchemy-async/
├── app/
│ ├── main.py
│ ├── api/
│ │ └── v1/
│ │ └── endpoints/
│ │ ├── auth.py
│ │ ├── users.py
│ │ └── items.py
│ ├── core/
│ │ ├── config.py
│ │ └── security.py
│ ├── db/
│ │ ├── base.py
│ │ ├── models.py
│ │ └── session.py
│ ├── models/
│ │ └── user.py
│ ├── repositories/
│ │ ├── user_repo.py
│ │ └── item_repo.py
│ ├── schemas/
│ │ ├── user.py
│ │ └── token.py
│ └── services/
│ ├── auth_service.py
│ └── user_service.py
├── tests/
│ ├── conftest.py
│ ├── test_auth.py
│ └── test_users.py
├── alembic/
│ └── versions/
├── docker/
│ ├── Dockerfile
│ └── docker-compose.yml
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
└── README.md
Core Engineering Principles
- Explicit dependencies and contracts between modules.
- Asynchronous I/O is the default for I/O-bound work.
- Strong typing and Pydantic models for runtime validation.
- Deterministic, idempotent operations with clear side effects.
- Clear separation of concerns and single source of truth per module.
- Observability through structured logging and metrics.
- Testability by design with test doubles and fixtures.
Code Construction Rules
- Use Async SQLAlchemy 2.0 for all DB interactions; avoid synchronous ORM calls.
- JWTs created with PyJWT or equivalent; secrets loaded from environment variable JWT_SECRET.
- Dependency-injected FastAPI routes; interfaces defined by type hints.
- Pydantic models for request/response validation; reuse schemas across layers.
- Alembic migrations for DB schema; do not alter DB in code outside migrations.
- Follow repository pattern for data access; keep business logic in services.
- All DB sessions must be async; use async_session with AsyncEngine.
- End-to-end tests must exercise authentication and protected routes.
- Do not hardcode credentials; read from environment and .env.
- Do not use in-memory SQLite for production.
Security and Production Rules
- Load JWT_SECRET from environment and rotate rotation-friendly keys when possible.
- Hash passwords with bcrypt (passlib) and store only hashed values.
- Use OAuth2PasswordBearer for protected endpoints and ensure access tokens expire (e.g., 15 minutes).
- Validate JWT claims (subject, expiry) on each request; reject invalid tokens with 401.
- Use TLS/HTTPS in production; configure CORS to limit origins.
- Do not log full tokens or sensitive payloads; mask token values in logs.
- Use Alembic for migrations; never alter schema at runtime without migrations.
Testing Checklist
- Unit tests for hashing, token creation, and validators.
- Integration tests for /auth/token and a sample protected endpoint against a test Postgres instance.
- End-to-end tests that spin up services with docker-compose and verify healthy startup.
Common Mistakes to Avoid
- Assuming synchronous DB calls are fine in an async app.
- Hardcoding secrets or using insecure defaults in production builds.
- Reusing a single JWT for long periods without rotation.
- Skipping migrations and evolution of DB schema.
FAQ
Q: Is this CLAUDE.md Template suitable for production?
A: Yes, when used with proper environment configuration, migrations, and security hardening per the template rules.
Q: Which stack does this template target?
A: FastAPI, PostgreSQL, OAuth2 JWT, SQLAlchemy 2.0 Async ORM.
Q: Can I replace SQLAlchemy with another ORM?
A: This template is tailored to SQLAlchemy 2.0 Async; adapting to another ORM requires updating all integration points.
Q: How do I run tests?
A: Use pytest with async support and a test PostgreSQL instance as described in the Testing Checklist.