

Also from Kynth Studios


Also from Kynth Studios


Also from Kynth Studios
1234567# Python FastAPI Backend Rules89## Framework and Core Dependencies1011For all Python API backend development, use **FastAPI** and its ecosystem:1213### Required Core Stack14- **FastAPI** (>=0.104.0) - Modern, fast web framework for building APIs15- **Uvicorn** (>=0.24.0) - ASGI server with `[standard]` extras for production features16- **Pydantic** (>=2.0.0) - Data validation using Python type annotations17- **Pydantic Settings** (>=2.0.0) - Settings management using Pydantic models1819### Database and ORM20- **SQLAlchemy** (>=2.0.0) - Modern ORM with async support21- **Alembic** (>=1.12.0) - Database migration tool22- **psycopg2-binary** (>=2.9.9) - PostgreSQL adapter (or appropriate database driver)2324### Development Tools25- **pytest** (>=7.4.0) - Testing framework26- **pytest-asyncio** (>=0.21.0) - Async test support27- **httpx** (>=0.25.0) - HTTP client for testing28- **black** (>=23.0.0) - Code formatter29- **isort** (>=5.12.0) - Import sorter30- **mypy** (>=1.6.0) - Static type checker3132## Code Structure and Patterns3334### Application Structure35```36backend/37├── app/38│ ├── __init__.py39│ ├── main.py # FastAPI app instance40│ ├── config.py # Pydantic Settings41│ ├── database.py # SQLAlchemy setup42│ ├── api/ # API routes43│ │ ├── __init__.py44│ │ └── *.py45│ ├── models/ # SQLAlchemy models46│ │ ├── __init__.py47│ │ └── *.py48│ ├── schemas/ # Pydantic schemas49│ │ ├── __init__.py50│ │ └── *.py51│ ├── crud/ # Database operations52│ │ ├── __init__.py53│ │ └── *.py54│ └── utils/ # Utility functions55│ ├── __init__.py56│ └── *.py57├── alembic/ # Database migrations58├── tests/ # Test files59├── pyproject.toml # Project dependencies60└── alembic.ini # Alembic configuration61```6263### FastAPI Application Setup6465```python66from fastapi import FastAPI67from fastapi.middleware.cors import CORSMiddleware68from .config import settings6970app = FastAPI(71 title=settings.PROJECT_NAME,72 version="0.1.0",73 description="API Description",74 openapi_url=f"{settings.API_V1_PREFIX}/openapi.json",75 docs_url=f"{settings.API_V1_PREFIX}/docs",76 redoc_url=f"{settings.API_V1_PREFIX}/redoc",77)7879# CORS middleware80app.add_middleware(81 CORSMiddleware,82 allow_origins=settings.ALLOWED_ORIGINS,83 allow_credentials=True,84 allow_methods=["*"],85 allow_headers=["*"],86)87```8889### Configuration Management9091Use **Pydantic Settings** for configuration:9293```python94from pydantic_settings import BaseSettings9596class Settings(BaseSettings):97 PROJECT_NAME: str98 API_V1_PREFIX: str = "/api/v1"99 DATABASE_URL: str100 ALLOWED_ORIGINS: list[str] = ["*"]101102 class Config:103 env_file = ".env"104 case_sensitive = True105106settings = Settings()107```108109### Database Setup110111Use **SQLAlchemy 2.0** with async support:112113```python114from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine115from sqlalchemy.orm import declarative_base, sessionmaker116117engine = create_async_engine(DATABASE_URL, echo=True)118AsyncSessionLocal = sessionmaker(119 engine, class_=AsyncSession, expire_on_commit=False120)121Base = declarative_base()122```123124### Dependency Injection125126Use FastAPI's dependency injection for database sessions:127128```python129from fastapi import Depends130from sqlalchemy.ext.asyncio import AsyncSession131132async def get_db() -> AsyncSession:133 async with AsyncSessionLocal() as session:134 yield session135136@app.get("/items/")137async def read_items(db: AsyncSession = Depends(get_db)):138 # Use db session139 pass140```141142### API Routes143144Organize routes using APIRouter:145146```python147from fastapi import APIRouter148149router = APIRouter()150151@router.get("/items/")152async def list_items():153 pass154155@router.post("/items/")156async def create_item():157 pass158```159160### Pydantic Schemas161162Use Pydantic v2 models for request/response validation:163164```python165from pydantic import BaseModel, Field166167class ItemCreate(BaseModel):168 name: str = Field(..., min_length=1, max_length=100)169 description: str | None = None170171class ItemResponse(BaseModel):172 id: int173 name: str174 description: str | None175176 class Config:177 from_attributes = True # Pydantic v2178```179180### CRUD Operations181182Separate database operations into CRUD modules:183184```python185from sqlalchemy.ext.asyncio import AsyncSession186from sqlalchemy import select187188async def create_item(db: AsyncSession, item_data: ItemCreate):189 db_item = Item(**item_data.model_dump())190 db.add(db_item)191 await db.commit()192 await db.refresh(db_item)193 return db_item194```195196### Testing197198Use **pytest** with **httpx** for API testing:199200```python201import pytest202from httpx import AsyncClient203from app.main import app204205@pytest.mark.asyncio206async def test_create_item():207 async with AsyncClient(app=app, base_url="http://test") as client:208 response = await client.post("/api/v1/items/", json={"name": "Test"})209 assert response.status_code == 201210```211212## Best Practices2132141. **Type Hints**: Always use type hints for function parameters and return types2152. **Async/Await**: Use async/await for all database operations and I/O-bound tasks2163. **Error Handling**: Use FastAPI's HTTPException for API errors2174. **Validation**: Leverage Pydantic for automatic request/response validation2185. **Documentation**: FastAPI auto-generates OpenAPI docs - use docstrings and response models2196. **Migrations**: Always use Alembic for database schema changes2207. **Testing**: Write tests for all API endpoints using pytest2218. **Code Quality**: Use black (line-length=100) and isort for formatting2229. **Type Checking**: Use mypy for static type checking223224## Prohibited Patterns225226- ❌ Do NOT use Flask, Django REST Framework, or other web frameworks227- ❌ Do NOT use synchronous database operations when async is available228- ❌ Do NOT bypass Pydantic validation229- ❌ Do NOT manually manage database migrations230- ❌ Do NOT use `@app.on_event("startup")` for database table creation (use Alembic)231232## Version Requirements233234- Python: >=3.11235- FastAPI: >=0.104.0236- SQLAlchemy: >=2.0.0 (use async patterns)237- Pydantic: >=2.0.0 (use v2 syntax)238
One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| tyrchen/geektime-bootcamp-ai.cursor/rules/rust-best-practices.mdc · 230 | Cursor rules | teststylearchdependencies+1 | 81/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-ai.cursor/rules/specify-rules.mdc · 230 | Cursor rules | stylearch | 52/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aisite/CLAUDE.md · 230 | CLAUDE.md | agent-behaviour | 25/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aiw3/raflow/CLAUDE.md · 230 | CLAUDE.md | agent-behaviour | 25/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aiw6/codereview-agent/CLAUDE.md · 230 | CLAUDE.md | setupbuildlint-formatarch+4 | 90/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aiw6/opencode-introspection/CLAUDE.md · 230 | CLAUDE.md | setupbuildtestlint-format+10 | 84/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aiw6/opencode-introspection/visualizer/CLAUDE.md · 230 | CLAUDE.md | setupbuildtestlint-format+9 | 78/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aiw6/simple-agent/CLAUDE.md · 230 | CLAUDE.md | setupbuildtestlint-format+10 | 84/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aiw7/genslides/backend/CLAUDE.md · 230 | CLAUDE.md | testlint-formatstylearch+6 | 100/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aiw7/genslides/frontend/CLAUDE.md · 230 | CLAUDE.md | teststylearchtypes+5 | 88/100 | 9 days ago | |
| tyrchen/geektime-bootcamp-aiw5/pg-mcp/CLAUDE.md · 230 | CLAUDE.md | setuptestlint-formatstyle+5 | 86/100 | 9 days ago |
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126 | Cursor rules | setupbuildtestlint-format+6 | 100/100 | 14 days ago | |
| TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 46 | Cursor rules | testlint-formatstylearch+5 | 100/100 | 14 days ago | |
| dodgecfr/combatfilms-webapp.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 14 days ago | |
| deifos/clipmira-subtitles.cursor/rules/frontend.mdc · 1 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 14 days ago | |
| markstev/mark-starter.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+6 | 99/100 | 14 days ago | |
| Allymahmoud/case-intake-platform.cursor/rules/frontend.mdc · 0 | Cursor rules | setuptestlint-formatstyle+7 | 99/100 | 14 days ago | |
| langflow-ai/langflow.cursor/rules/docs_development.mdc · 153k | Cursor rules | setupbuildtestlint-format+7 | 97/100 | 14 days ago | |
| bybren-llc/safe-agentic-workflow.cursor/rules/10-backend-python.mdc · 399 | Cursor rules | testlint-formatstylegit+4 | 97/100 | today |
A badge carrying the measured quality of the strongest agent config file in this repository, out of 100. It reads from this index every time somebody loads your page, so it changes when the measurement changes and there is nothing to keep up to date. Free, no account, and the value is not something you or we can set by hand.
[](https://rulestack.kynth.studio/configs/tyrchen-geektime-bootcamp-ai-cursor-rules-python-fastapi-backend)Would rather not hotlink us? Every badge is also served in shields.io’s endpoint schema, so shields renders the image and your readers never talk to our domain:
Published by Toolproof, the masthead over this index and eight others. The method behind the number is at toolproof.kynth.studio/methodology, and the whole thing is readable as JSON with no key at /api.