Cursor Fastapi 编码规范:来自 PatrickJS/awesome-cursorrules (40k stars) 的 fas,适用于各类文档与内容的智能化处理。
Cursor Fastapi 编码规范:来自 PatrickJS/awesome-cursorrules (40k stars) 的 fas,适用于各类文档与内容的智能化处理。
**文件来源:** PatrickJS/awesome-cursorrules → `rules/fastapi-production-architecture-cursorrules-prompt-file.mdc`
**原仓库:** https://github.com/PatrickJS/awesome-cursorrules
**评分:** ⭐ 仓库 40k stars (社区最权威 Cursor rules 合集)
把 `fastapi-production-architecture-cursorrules-prompt-file.mdc` 这条 Cursor 编码规则打包成可调用的 AI skill,帮你把代码生成统一到一致的标准上。
> Cursor rules for FastAPI services with router/service/repository boundaries, typed provider adapters, bulkhead isolation, idempotency, and domain exceptions.
globs: **/*
alwaysApply: false
---
# FastAPI Production Architecture Rules
# Principles for production-ready FastAPI services.
## LAYER ARCHITECTURE (Principles A1-A8)
This codebase follows strict 4-layer architecture: Router → Service → Repository → ORM/HTTP/Storage.
Imports flow downward only. Each layer has hard boundaries you must NOT cross.
### Router rules (app/routers/**)
- Handlers are THIN: ≤10 lines of executable code per handler
- Allowed imports: fastapi, app.schemas.*, app.core.deps, app.services.*
- FORBIDDEN imports: sqlalchemy, httpx, boto3, app.models.*, app.repositories.*
- Every endpoint declares response_model= for OpenAPI fidelity
- Every protected/business endpoint requires user_id: str = Depends(get_current_user_id)
- Public endpoints (health checks, webhooks, callbacks) are exempt from auth
- Business logic lives in services. Routers parse input, call one service method, return response.
GOOD:
@router.post("/wallet/charge", response_model=WalletResponse, status_code=201)
async def charge(
req: ChargeRequest,
user_id: str = Depends(get_current_user_id),
svc: WalletUserService = Depends(get_wallet_service),
) -> WalletResponse:
wallet = await svc.charge(
user_id=user_id,
amount=req.amount,
idempotency_key=req.idempotency_key,
)
return WalletResponse.from_domain(wallet)
BAD (business logic + SQL in router):
@router.post("/wallet/charge")
async def charge(req: ChargeRequest, db: Session = Depends(get_db)):
wallet = db.query(Wallet).filter(Wallet.user_id == user_id).with_for_update().one()
...
### Service rules (app/services/**)
- FORBIDDEN imports: sqlalchemy, httpx, boto3, redis, FastAPI Request/Response/HTTPException
- Constructor injects Protocol-typed dependencies, not concrete classes
- Raise domain exceptions (InsufficientFundsError), not HTTPException
GOOD:
from app.repositories.protocols import WalletRepoProtocol
class WalletUserService:
def __init__(self, repo: WalletRepoProtocol): # Protocol, not SQLAlchemy Session
self._repo = repo
BAD:
from sqlalchemy.orm import Session
class WalletUserService:
def __init__(self, db: Session): ... # Wrong — service depends on infrastructure
### Repository rules (app/repositories/**)
- ONLY layer allowed to import sqlalchemy
- Implements Protocol from app/repositories/protocols.py
- Returns domain objects, not ORM models
- Every query scoped by user_id (multi-tenancy)
### Provider rules (app/providers/**)
- ONLY layer allowed to import httpx directly
- Returns GenerateResult | ProviderError — NEVER raw dict
- Uses per-provider httpx.AsyncClient (bulkhead pattern)
## FILE SIZE RULES (Principle A1)
| LOC | State | Action |
|----------|--------|---------------------------------------------|
| 0–399 | Green | None. |
| 400–599 | Yellow | Plan split. Add TODO(decompose) header. |
| 600+ | Red | BLOCK merge.
...(完整内容在原仓库)...
有问题或建议,在本 skill 下留言。
把 `fastapi-production-architecture-cursorrules-prompt-file.mdc` 这条 Cursor 编码规则打包成可调用的 AI skill,帮你把代码生成统一到一致的标准上。
> Cursor rules for FastAPI services with router/service/repository boundaries, typed provider adapters, bulkhead isolation, idempotency, and domain exceptions.