@baselane/packs 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/aliases.js +1 -0
  2. package/package.json +2 -2
  3. package/packs/database-review/pack.json +75 -9
  4. package/packs/database-review/rendered/.claude/agents/database-reviewer.md +75 -2
  5. package/packs/database-review/rendered/.claude/commands/migration-review.md +6 -0
  6. package/packs/database-review/rendered/.claude/settings.json +11 -0
  7. package/packs/database-review/rendered/.claude/skills/database-migrations/SKILL.md +431 -0
  8. package/packs/database-review/rendered/.claude/skills/mysql-patterns/SKILL.md +414 -0
  9. package/packs/database-review/rendered/.claude/skills/postgres-patterns/SKILL.md +149 -0
  10. package/packs/database-review/rendered/.github/copilot-instructions.md +1096 -14
  11. package/packs/database-review/rendered/AGENTS.md +45 -16
  12. package/packs/database-review/rendered/CLAUDE.md +4 -0
  13. package/packs/database-review/rendered/GEMINI.md +987 -0
  14. package/packs/go-rules/pack.json +65 -9
  15. package/packs/go-rules/rendered/.claude/agents/go-build-resolver.md +90 -0
  16. package/packs/go-rules/rendered/.claude/agents/go-reviewer.md +72 -2
  17. package/packs/go-rules/rendered/.claude/commands/go-build.md +6 -0
  18. package/packs/go-rules/rendered/.claude/commands/go-review.md +1 -1
  19. package/packs/go-rules/rendered/.claude/commands/go-test.md +6 -0
  20. package/packs/go-rules/rendered/.claude/settings.json +9 -0
  21. package/packs/go-rules/rendered/.claude/skills/golang-patterns/SKILL.md +673 -0
  22. package/packs/go-rules/rendered/.claude/skills/golang-testing/SKILL.md +719 -0
  23. package/packs/go-rules/rendered/.github/copilot-instructions.md +1783 -7
  24. package/packs/go-rules/rendered/AGENTS.md +244 -8
  25. package/packs/go-rules/rendered/CLAUDE.md +5 -0
  26. package/packs/go-rules/rendered/GEMINI.md +1394 -0
  27. package/packs/python-rules/pack.json +87 -10
  28. package/packs/python-rules/rendered/.claude/agents/django-reviewer.md +159 -0
  29. package/packs/python-rules/rendered/.claude/agents/fastapi-reviewer.md +70 -0
  30. package/packs/python-rules/rendered/.claude/agents/python-reviewer.md +92 -2
  31. package/packs/python-rules/rendered/.claude/commands/django-review.md +6 -0
  32. package/packs/python-rules/rendered/.claude/commands/fastapi-review.md +6 -0
  33. package/packs/python-rules/rendered/.claude/commands/python-review.md +1 -1
  34. package/packs/python-rules/rendered/.claude/settings.json +1 -1
  35. package/packs/python-rules/rendered/.claude/skills/django-security/SKILL.md +642 -0
  36. package/packs/python-rules/rendered/.claude/skills/django-tdd/SKILL.md +728 -0
  37. package/packs/python-rules/rendered/.claude/skills/fastapi-patterns/SKILL.md +512 -0
  38. package/packs/python-rules/rendered/.claude/skills/python-patterns/SKILL.md +749 -0
  39. package/packs/python-rules/rendered/.claude/skills/python-testing/SKILL.md +815 -0
  40. package/packs/python-rules/rendered/.github/copilot-instructions.md +3815 -12
  41. package/packs/python-rules/rendered/AGENTS.md +73 -13
  42. package/packs/python-rules/rendered/CLAUDE.md +9 -0
  43. package/packs/python-rules/rendered/GEMINI.md +3448 -0
  44. package/packs/security-review/pack.json +51 -7
  45. package/packs/security-review/rendered/.claude/agents/security-reviewer.md +29 -2
  46. package/packs/security-review/rendered/.claude/settings.json +11 -0
  47. package/packs/security-review/rendered/.claude/skills/security-review/SKILL.md +302 -0
  48. package/packs/security-review/rendered/.claude/skills/security-review/cloud-infrastructure-security.md +171 -0
  49. package/packs/security-review/rendered/.claude/skills/security-scan-config/SKILL.md +56 -0
  50. package/packs/security-review/rendered/.github/copilot-instructions.md +658 -15
  51. package/packs/security-review/rendered/AGENTS.md +283 -17
  52. package/packs/security-review/rendered/CLAUDE.md +2 -0
  53. package/packs/security-review/rendered/GEMINI.md +352 -0
  54. package/packs/software-engineer-harness/pack.json +249 -13
  55. package/packs/software-engineer-harness/rendered/.claude/agents/code-explorer.md +67 -0
  56. package/packs/software-engineer-harness/rendered/.claude/agents/performance-optimizer.md +444 -0
  57. package/packs/software-engineer-harness/rendered/.claude/agents/pr-test-analyzer.md +43 -0
  58. package/packs/software-engineer-harness/rendered/.claude/commands/feature-dev.md +6 -0
  59. package/packs/software-engineer-harness/rendered/.claude/settings.json +29 -0
  60. package/packs/software-engineer-harness/rendered/.claude/skills/api-design/SKILL.md +522 -0
  61. package/packs/software-engineer-harness/rendered/.claude/skills/architecture-decision-records/SKILL.md +178 -0
  62. package/packs/software-engineer-harness/rendered/.claude/skills/backend-patterns/SKILL.md +560 -0
  63. package/packs/software-engineer-harness/rendered/.claude/skills/codebase-onboarding/SKILL.md +232 -0
  64. package/packs/software-engineer-harness/rendered/.claude/skills/deployment-patterns/SKILL.md +426 -0
  65. package/packs/software-engineer-harness/rendered/.claude/skills/docker-patterns/SKILL.md +363 -0
  66. package/packs/software-engineer-harness/rendered/.claude/skills/e2e-testing/SKILL.md +325 -0
  67. package/packs/software-engineer-harness/rendered/.claude/skills/tdd-workflow/SKILL.md +580 -0
  68. package/packs/software-engineer-harness/rendered/.github/copilot-instructions.md +3948 -2
  69. package/packs/software-engineer-harness/rendered/AGENTS.md +194 -4
  70. package/packs/software-engineer-harness/rendered/CLAUDE.md +20 -0
  71. package/packs/software-engineer-harness/rendered/GEMINI.md +3208 -0
  72. package/packs/typescript-rules/pack.json +68 -5
  73. package/packs/typescript-rules/rendered/.claude/agents/react-reviewer.md +165 -0
  74. package/packs/typescript-rules/rendered/.claude/agents/type-design-analyzer.md +48 -0
  75. package/packs/typescript-rules/rendered/.claude/commands/react-review.md +6 -0
  76. package/packs/typescript-rules/rendered/.claude/settings.json +9 -0
  77. package/packs/typescript-rules/rendered/.claude/skills/react-patterns/SKILL.md +340 -0
  78. package/packs/typescript-rules/rendered/.claude/skills/react-performance/SKILL.md +573 -0
  79. package/packs/typescript-rules/rendered/.claude/skills/react-testing/SKILL.md +422 -0
  80. package/packs/typescript-rules/rendered/.github/copilot-instructions.md +2459 -53
  81. package/packs/typescript-rules/rendered/AGENTS.md +893 -17
  82. package/packs/typescript-rules/rendered/CLAUDE.md +6 -0
  83. package/packs/typescript-rules/rendered/GEMINI.md +1335 -0
  84. package/packs/ecc-essentials/pack.json +0 -93
  85. package/packs/ecc-essentials/rendered/.claude/settings.json +0 -37
  86. package/packs/ecc-essentials/rendered/.github/copilot-instructions.md +0 -110
  87. package/packs/ecc-essentials/rendered/AGENTS.md +0 -74
  88. package/packs/ecc-essentials/rendered/CLAUDE.md +0 -14
  89. package/packs/ecc-essentials/rendered/GEMINI.md +0 -25
  90. /package/packs/{ecc-essentials → software-engineer-harness}/rendered/.claude/agents/build-error-resolver.md +0 -0
  91. /package/packs/{ecc-essentials → software-engineer-harness}/rendered/.claude/agents/refactor-cleaner.md +0 -0
  92. /package/packs/{ecc-essentials → software-engineer-harness}/rendered/.claude/agents/silent-failure-hunter.md +0 -0
  93. /package/packs/{ecc-essentials → software-engineer-harness}/rendered/.claude/agents/tdd-guide.md +0 -0
  94. /package/packs/{ecc-essentials → software-engineer-harness}/rendered/.claude/commands/fix-build.md +0 -0
  95. /package/packs/{ecc-essentials → software-engineer-harness}/rendered/.claude/commands/hunt-silent-failures.md +0 -0
  96. /package/packs/{ecc-essentials → software-engineer-harness}/rendered/.claude/commands/tdd.md +0 -0
  97. /package/packs/{ecc-essentials → software-engineer-harness}/rendered/.claude/skills/tdd-red-green-refactor/SKILL.md +0 -0
@@ -0,0 +1,512 @@
1
+ ---
2
+ name: fastapi-patterns
3
+ description: FastAPI project layout, app factory/lifespan, pydantic-settings config, Pydantic v2 request/response schemas, async dependency injection, router design, a transactional service layer, and httpx+pytest testing. Use when building or reviewing a FastAPI application.
4
+ ---
5
+
6
+ # FastAPI Patterns
7
+
8
+ Modern, production-grade FastAPI development: project layout, Pydantic v2 schemas, dependency injection, async patterns, auth, transactional service methods, and testing.
9
+
10
+ ## Project Structure
11
+
12
+ ```text
13
+ my_app/
14
+ |-- app/
15
+ | |-- main.py # App factory, lifespan, middleware
16
+ | |-- config.py # Settings via pydantic-settings
17
+ | |-- dependencies.py # Shared FastAPI dependencies
18
+ | |-- database.py # SQLAlchemy engine + session
19
+ | |-- routers/
20
+ | | `-- users.py
21
+ | |-- models/ # SQLAlchemy ORM models
22
+ | | `-- user.py
23
+ | |-- schemas/ # Pydantic request/response schemas
24
+ | | `-- user.py
25
+ | `-- services/ # Business logic layer
26
+ | `-- user_service.py
27
+ |-- tests/
28
+ | |-- conftest.py
29
+ | `-- test_users.py
30
+ |-- pyproject.toml
31
+ `-- .env
32
+ ```
33
+
34
+ ---
35
+
36
+ ## App Factory and Lifespan
37
+
38
+ ```python
39
+ # app/main.py
40
+ from contextlib import asynccontextmanager
41
+ from fastapi import FastAPI
42
+ from fastapi.middleware.cors import CORSMiddleware
43
+
44
+ from app.config import settings
45
+ from app.database import engine, Base
46
+ from app.routers import users
47
+
48
+
49
+ @asynccontextmanager
50
+ async def lifespan(app: FastAPI):
51
+ # Automatically create tables on startup for ease of use in dev/demo environments.
52
+ # For strict production applications, manage schemas via Alembic migrations instead.
53
+ async with engine.begin() as conn:
54
+ await conn.run_sync(Base.metadata.create_all)
55
+ yield
56
+ # Shutdown: close pooled resources.
57
+ await engine.dispose()
58
+
59
+
60
+ def create_app() -> FastAPI:
61
+ app = FastAPI(
62
+ title=settings.app_name,
63
+ version=settings.app_version,
64
+ lifespan=lifespan,
65
+ )
66
+
67
+ app.add_middleware(
68
+ CORSMiddleware,
69
+ allow_origins=settings.allowed_origins,
70
+ allow_credentials=settings.allow_credentials,
71
+ allow_methods=settings.allowed_methods,
72
+ allow_headers=settings.allowed_headers,
73
+ )
74
+
75
+ app.include_router(users.router, prefix="/users", tags=["users"])
76
+
77
+ return app
78
+
79
+
80
+ app = create_app()
81
+ ```
82
+
83
+ ---
84
+
85
+ ## Configuration with pydantic-settings
86
+
87
+ ```python
88
+ # app/config.py
89
+ from pydantic_settings import BaseSettings, SettingsConfigDict
90
+
91
+
92
+ class Settings(BaseSettings):
93
+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
94
+
95
+ app_name: str = "My App"
96
+ app_version: str = "0.1.0"
97
+ debug: bool = False
98
+
99
+ database_url: str
100
+ secret_key: str
101
+ algorithm: str = "HS256"
102
+ access_token_expire_minutes: int = 30
103
+
104
+ # Pydantic-settings v2 safely evaluates mutable list literals directly
105
+ allowed_origins: list[str] = ["http://localhost:3000"]
106
+ allowed_methods: list[str] = ["GET", "POST", "PATCH", "DELETE", "OPTIONS"]
107
+ allowed_headers: list[str] = ["Authorization", "Content-Type"]
108
+ allow_credentials: bool = True
109
+
110
+
111
+ settings = Settings()
112
+ ```
113
+
114
+ ---
115
+
116
+ ## Pydantic Schemas (v2)
117
+
118
+ ```python
119
+ # app/schemas/user.py
120
+ from datetime import datetime
121
+ from pydantic import BaseModel, EmailStr, Field, model_validator
122
+
123
+
124
+ class UserBase(BaseModel):
125
+ email: EmailStr
126
+ username: str = Field(min_length=3, max_length=50)
127
+
128
+
129
+ class UserCreate(UserBase):
130
+ password: str = Field(min_length=8)
131
+ password_confirm: str
132
+
133
+ @model_validator(mode="after")
134
+ def passwords_match(self) -> "UserCreate":
135
+ if self.password != self.password_confirm:
136
+ raise ValueError("Passwords do not match")
137
+ return self
138
+
139
+
140
+ class UserUpdate(BaseModel):
141
+ username: str | None = Field(default=None, min_length=3, max_length=50)
142
+ email: EmailStr | None = None
143
+
144
+
145
+ class UserResponse(UserBase):
146
+ id: int
147
+ is_active: bool
148
+ created_at: datetime
149
+
150
+ model_config = {"from_attributes": True}
151
+
152
+
153
+ class UserListResponse(BaseModel):
154
+ total: int
155
+ items: list[UserResponse]
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Dependency Injection
161
+
162
+ ```python
163
+ # app/dependencies.py
164
+ from typing import Annotated, AsyncGenerator
165
+ from fastapi import Depends, HTTPException, status
166
+ from fastapi.security import OAuth2PasswordBearer
167
+ from jose import JWTError, jwt
168
+ from sqlalchemy.ext.asyncio import AsyncSession
169
+
170
+ from app.config import settings
171
+ from app.database import AsyncSessionLocal
172
+ from app.models.user import User
173
+
174
+ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/users/token")
175
+
176
+
177
+ async def get_db() -> AsyncGenerator[AsyncSession, None]:
178
+ async with AsyncSessionLocal() as session:
179
+ try:
180
+ yield session
181
+ except Exception:
182
+ await session.rollback()
183
+ raise
184
+
185
+
186
+ async def get_current_user(
187
+ token: Annotated[str, Depends(oauth2_scheme)],
188
+ db: Annotated[AsyncSession, Depends(get_db)],
189
+ ) -> User:
190
+ credentials_exception = HTTPException(
191
+ status_code=status.HTTP_401_UNAUTHORIZED,
192
+ detail="Could not validate credentials",
193
+ headers={"WWW-Authenticate": "Bearer"},
194
+ )
195
+ try:
196
+ payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
197
+ subject = payload.get("sub")
198
+ if subject is None:
199
+ raise credentials_exception
200
+ user_id = int(subject)
201
+ except (JWTError, TypeError, ValueError):
202
+ raise credentials_exception
203
+
204
+ user = await db.get(User, user_id)
205
+ if user is None:
206
+ raise credentials_exception
207
+ return user
208
+
209
+
210
+ async def get_current_active_user(
211
+ current_user: Annotated[User, Depends(get_current_user)],
212
+ ) -> User:
213
+ if not current_user.is_active:
214
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user")
215
+ return current_user
216
+
217
+
218
+ DbDep = Annotated[AsyncSession, Depends(get_db)]
219
+ CurrentUserDep = Annotated[User, Depends(get_current_user)]
220
+ ActiveUserDep = Annotated[User, Depends(get_current_active_user)]
221
+ ```
222
+
223
+ ---
224
+
225
+ ## Router and Endpoint Design
226
+
227
+ ```python
228
+ # app/routers/users.py
229
+ from typing import Annotated
230
+ from fastapi import APIRouter, HTTPException, Query, status
231
+ from fastapi.security import OAuth2PasswordRequestForm
232
+
233
+ from app.dependencies import ActiveUserDep, DbDep
234
+ from app.schemas.user import UserCreate, UserResponse, UserUpdate, UserListResponse
235
+ from app.services.user_service import DuplicateUserError, UserService
236
+
237
+ router = APIRouter()
238
+
239
+
240
+ @router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
241
+ async def create_user(payload: UserCreate, db: DbDep) -> UserResponse:
242
+ service = UserService(db)
243
+ try:
244
+ return await service.create(payload)
245
+ except DuplicateUserError:
246
+ raise HTTPException(status_code=400, detail="Email already registered")
247
+
248
+
249
+ @router.get("/me", response_model=UserResponse)
250
+ async def get_me(current_user: ActiveUserDep) -> UserResponse:
251
+ return current_user
252
+
253
+
254
+ @router.get("/", response_model=UserListResponse)
255
+ async def list_users(
256
+ db: DbDep,
257
+ current_user: ActiveUserDep,
258
+ skip: Annotated[int, Query(ge=0)] = 0,
259
+ limit: Annotated[int, Query(ge=1, le=100)] = 20,
260
+ ) -> UserListResponse:
261
+ service = UserService(db)
262
+ users, total = await service.list(skip=skip, limit=limit)
263
+ return UserListResponse(total=total, items=users)
264
+
265
+
266
+ @router.patch("/{user_id}", response_model=UserResponse)
267
+ async def update_user(
268
+ user_id: int,
269
+ payload: UserUpdate,
270
+ db: DbDep,
271
+ current_user: ActiveUserDep,
272
+ ) -> UserResponse:
273
+ if current_user.id != user_id:
274
+ raise HTTPException(status_code=403, detail="Not authorized")
275
+ service = UserService(db)
276
+ try:
277
+ user = await service.update(user_id, payload)
278
+ except DuplicateUserError:
279
+ raise HTTPException(status_code=400, detail="Email already registered")
280
+ if user is None:
281
+ raise HTTPException(status_code=404, detail="User not found")
282
+ return user
283
+
284
+
285
+ @router.post("/token")
286
+ async def login(
287
+ form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
288
+ db: DbDep,
289
+ ) -> dict[str, str]:
290
+ service = UserService(db)
291
+ token = await service.authenticate(form_data.username, form_data.password)
292
+ if token is None:
293
+ raise HTTPException(
294
+ status_code=status.HTTP_401_UNAUTHORIZED,
295
+ detail="Incorrect username or password",
296
+ headers={"WWW-Authenticate": "Bearer"},
297
+ )
298
+ return {"access_token": token, "token_type": "bearer"}
299
+ ```
300
+
301
+ ---
302
+
303
+ ## Service Layer
304
+
305
+ ```python
306
+ # app/services/user_service.py
307
+ from datetime import datetime, timedelta, timezone
308
+
309
+ from jose import jwt
310
+ from passlib.context import CryptContext
311
+ from sqlalchemy import func, select
312
+ from sqlalchemy.exc import IntegrityError
313
+ from sqlalchemy.ext.asyncio import AsyncSession
314
+
315
+ from app.config import settings
316
+ from app.models.user import User
317
+ from app.schemas.user import UserCreate, UserUpdate
318
+
319
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
320
+
321
+
322
+ class DuplicateUserError(Exception):
323
+ """Raised when a unique user field conflicts with an existing row."""
324
+
325
+
326
+ class UserService:
327
+ def __init__(self, db: AsyncSession) -> None:
328
+ self.db = db
329
+
330
+ async def get_by_email(self, email: str) -> User | None:
331
+ result = await self.db.execute(select(User).where(User.email == email))
332
+ return result.scalar_one_or_none()
333
+
334
+ async def create(self, payload: UserCreate) -> User:
335
+ user = User(
336
+ email=payload.email,
337
+ username=payload.username,
338
+ hashed_password=pwd_context.hash(payload.password),
339
+ )
340
+ self.db.add(user)
341
+ try:
342
+ # Rely on atomic DB constraints rather than race-prone application-level prechecks
343
+ await self.db.commit()
344
+ except IntegrityError as exc:
345
+ await self.db.rollback()
346
+ raise DuplicateUserError from exc
347
+ await self.db.refresh(user)
348
+ return user
349
+
350
+ async def list(self, skip: int = 0, limit: int = 20) -> tuple[list[User], int]:
351
+ total_result = await self.db.execute(select(func.count(User.id)))
352
+ total = total_result.scalar_one()
353
+ # Enforce explicit deterministic ordering to ensure reliable pagination
354
+ result = await self.db.execute(
355
+ select(User).order_by(User.id).offset(skip).limit(limit)
356
+ )
357
+ return list(result.scalars()), total
358
+
359
+ async def update(self, user_id: int, payload: UserUpdate) -> User | None:
360
+ user = await self.db.get(User, user_id)
361
+ if user is None:
362
+ return None
363
+ for field, value in payload.model_dump(exclude_unset=True).items():
364
+ setattr(user, field, value)
365
+ try:
366
+ await self.db.commit()
367
+ except IntegrityError as exc:
368
+ await self.db.rollback()
369
+ raise DuplicateUserError from exc
370
+ await self.db.refresh(user)
371
+ return user
372
+
373
+ async def authenticate(self, email: str, password: str) -> str | None:
374
+ user = await self.get_by_email(email)
375
+ if user is None or not pwd_context.verify(password, user.hashed_password):
376
+ return None
377
+ expire = datetime.now(timezone.utc) + timedelta(
378
+ minutes=settings.access_token_expire_minutes
379
+ )
380
+ return jwt.encode(
381
+ {"sub": str(user.id), "exp": expire},
382
+ settings.secret_key,
383
+ algorithm=settings.algorithm,
384
+ )
385
+ ```
386
+
387
+ > **Note on Database Design:** Application-level unique handling requires an underlying unique database index (e.g., `unique=True` on your SQLAlchemy mapping attributes). Without underlying constraints, application layer error-catching cannot safely prevent concurrent race conditions.
388
+
389
+ ---
390
+
391
+ ## Testing with httpx and pytest
392
+
393
+ ```python
394
+ # tests/conftest.py
395
+ import pytest_asyncio
396
+ from httpx import ASGITransport, AsyncClient
397
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
398
+
399
+ from app.database import Base
400
+ from app.dependencies import get_db
401
+ from app.main import create_app
402
+
403
+ TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
404
+
405
+ engine = create_async_engine(TEST_DATABASE_URL)
406
+ TestingSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
407
+
408
+
409
+ @pytest_asyncio.fixture(autouse=True)
410
+ async def setup_db():
411
+ async with engine.begin() as conn:
412
+ await conn.run_sync(Base.metadata.create_all)
413
+ yield
414
+ async with engine.begin() as conn:
415
+ await conn.run_sync(Base.metadata.drop_all)
416
+
417
+
418
+ @pytest_asyncio.fixture
419
+ async def db_session():
420
+ async with TestingSessionLocal() as session:
421
+ yield session
422
+ await session.rollback()
423
+
424
+
425
+ @pytest_asyncio.fixture
426
+ async def client(db_session: AsyncSession):
427
+ app = create_app()
428
+
429
+ async def override_get_db():
430
+ yield db_session
431
+
432
+ app.dependency_overrides[get_db] = override_get_db
433
+
434
+ async with AsyncClient(
435
+ transport=ASGITransport(app=app), base_url="http://test"
436
+ ) as ac:
437
+ yield ac
438
+
439
+
440
+ @pytest_asyncio.fixture
441
+ async def registered_user(client: AsyncClient) -> dict:
442
+ resp = await client.post("/users/", json={
443
+ "email": "test@example.com",
444
+ "username": "testuser",
445
+ "password": "securepass1",
446
+ "password_confirm": "securepass1",
447
+ })
448
+ assert resp.status_code == 201
449
+ return resp.json()
450
+
451
+
452
+ @pytest_asyncio.fixture
453
+ async def auth_token(client: AsyncClient, registered_user: dict) -> str:
454
+ resp = await client.post("/users/token", data={
455
+ "username": "test@example.com",
456
+ "password": "securepass1",
457
+ })
458
+ assert resp.status_code == 200
459
+ return resp.json()["access_token"]
460
+
461
+
462
+ @pytest_asyncio.fixture
463
+ async def auth_client(client: AsyncClient, auth_token: str) -> AsyncClient:
464
+ client.headers.update({"Authorization": f"Bearer {auth_token}"})
465
+ return client
466
+ ```
467
+
468
+ ---
469
+
470
+ ## Anti-Patterns
471
+
472
+ ```python
473
+ # Bad: business logic inside route handlers.
474
+ @router.post("/users/")
475
+ async def create_user(payload: UserCreate, db: DbDep):
476
+ hashed = bcrypt.hash(payload.password)
477
+ user = User(email=payload.email, hashed_password=hashed)
478
+ db.add(user)
479
+ await db.commit()
480
+ return user
481
+
482
+ # Good: thin route, transactional service handling.
483
+ @router.post("/users/", response_model=UserResponse, status_code=201)
484
+ async def create_user(payload: UserCreate, db: DbDep):
485
+ try:
486
+ return await UserService(db).create(payload)
487
+ except DuplicateUserError:
488
+ raise HTTPException(status_code=400, detail="Email already registered")
489
+
490
+
491
+ # Bad: sync DB calls in async routes block the event loop.
492
+ @router.get("/items/")
493
+ async def list_items(db: Session = Depends(get_db)):
494
+ return db.query(Item).all()
495
+
496
+ # Good: use async SQLAlchemy executions.
497
+ @router.get("/items/")
498
+ async def list_items(db: AsyncSession = Depends(get_db)):
499
+ result = await db.execute(select(Item))
500
+ return result.scalars().all()
501
+ ```
502
+
503
+ ---
504
+
505
+ ## Best Practices
506
+
507
+ - Always declare a typed `response_model` to prevent accidental PII/data leaks and output clean OpenAPI schemas.
508
+ - Consolidate standard middleware dependency injections via type-aliasing: `DbDep = Annotated[AsyncSession, Depends(get_db)]`.
509
+ - Wrap database mutation boundaries gracefully within transactions inside your service layer, catching structural database errors directly.
510
+ - Parse JWT parameters defensively, expecting potential string/integer cast mismatches from modern payload variations.
511
+ - Enforce deterministic sorting (e.g., `.order_by(Model.id)`) on all offset/limit paginated endpoints to avoid data skips.
512
+ - Isolate authorization checks from core authentication dependencies to provide precise REST status signals (`401` vs `403`).