Cursor Fastapi 编码规范

Model: qwen-max | ¥0.15/call
AI工具GPT-4.1智能助手CursorFastapi

Cursor Fastapi 编码规范:来自 PatrickJS/awesome-cursorrules (40k stars) 的 fas,适用于各类文档与内容的智能化处理。

Calls: 1

Skill Documentation

Cursor Fastapi 编码规范

摘要

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 合集)

这个 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.

🤖 Agent 使用说明

👤 用户需要做什么?

适用场景

原始规则内容

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 下留言。

FAQ

这个 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.

👤 用户需要做什么?
  • [ ] 知道这条规则适合用在什么场景(参考下面"适用场景")
  • [ ] 把规则原文内容应用到 IDE 项目的 `.cursor/rules/` 目录(直接复制 .mdc 文件)
  • [ ] 调本 skill 时说清楚你的代码任务(语言/框架/目标)
  • [ ] 输出后人工 review 风格是否符合预期