SuperAPI AI Directory

fastapi

Coding & development

View repository

Updated 10-16 07:23

About this skill

FastAPI Backend Development Standards

Trigger Conditions

  • Develop FastAPI projects
  • Implement async REST APIs
  • Use SQLAlchemy 2.0 async ORM
  • Use Pydantic v2 for data validation
  • Implement JWT / Redis Token authentication
  • Implement role-based permission control
  • Develop youlai-fastapi admin backend modules

Part 1: Tech Stack

Layer Choice Description
Web Framework FastAPI 0.115+ Async-native, Pydantic v2 integration, automatic OpenAPI docs
ASGI Server Uvicorn 0.30+ Officially recommended by FastAPI
ORM SQLAlchemy 2.0 + asyncpg Mapped + mapped_column Declarative, full async support
Data Validation Pydantic v2 Rust core, native FastAPI integration
Database PostgreSQL 16+ Production-grade, asyncpg async driver
Cache Redis 7.x redis[hiredis] Async client
Authentication PyJWT 2.x + bcrypt 4.x JWT signing/verification, password hashing
Logging loguru 0.7+ Zero-config, colored output, automatic rotate
Package Management uv Written in Rust, 10-100x pip speed
Code Quality ruff + mypy Lint + formatting + static type checking
Testing pytest + httpx httpx AsyncClient directly tests FastAPI

Part 2: Directory Structure

The directory structure follows the community benchmark zhanymkanov/fastapi-best-practices .

youlai-fastapi/
├── app/
│   ├── __init__.py
│   ├── main.py                 # FastAPI 入口:挂载路由、中间件、异常处理器
│   ├── config.py               # Pydantic Settings
│   ├── database.py             # 异步引擎 + session + get_db
│   ├── redis.py                # Redis 连接池 + get_redis
│   ├── response.py             # Result[T] + ResultCode 统一响应
│   ├── exceptions.py           # BusinessException + 全局异常处理器
│   ├── enums.py                 # 全局枚举
│   ├── pagination.py           # PageQuery / PageResult
│   ├── constants.py            # 全局常量:安全前缀 / REDIS_ 前缀 / 系统级
│   ├── dependencies.py         # 全局依赖 get_current_user / require_perm
│   ├── middleware.py           # CORS + 请求日志 + 限流
│   ├── registry.py             # 导入全部域模型,触发 Base.metadata 注册(Base/Mixin 在 database.py)
│   ├── auth/                   # 认证域:router.py / schemas.py / service.py / token.py / utils.py
│   ├── captcha/                # 验证码:service.py / constants.py
│   ├── system/                 # 系统管理域
│   │   ├── user/  role/  menu/  dept/  dict/  log/
│   │   │   └── 各含 router.py  schemas.py  service.py  models.py
│   │   │       (role/ 含 constants.py、data_permission.py;log/ 含 constants.py、operation_log.py)
│   │   ├── config/             # 仅 models.py + router.py(配置内联,无 schemas/service)
│   │   └── notice/             # 仅 models.py + router.py
│   └── tool/                   # 工具与集成域
│       └── file/  codegen/  wxma/  sse/   # 文件 / 代码生成 / 微信小程序 / 服务端推送
├── alembic/                    # 数据库迁移
├── alembic.ini
├── tests/
│   ├── conftest.py
│   ├── auth/test_auth.py       # 按业务域镜像
│   └── test_result_code.py     # 全局
├── Dockerfile
├── docker-compose.yml
├── pyproject.toml              # uv 依赖管理
├── .env.example
├── .gitignore
└── README.md

Design Principles:

  • Organize by business domain: each domain directory is self-contained router/schemas/models/service(including constants/dependencies/exceptionsas needed), with domains importing each other through explicit module names.
  • models/ Only holds the ORM base class and global registration; pure ORM does not depend on any business layer.
  • Global infrastructure (config / database / redis / response / exceptions / pagination / constants / dependencies / middleware) is laid out flat under the app/ root and shared by all domains.
  • No core/ common/ framework/ modules/ layered packages.

Part 3: Naming Conventions

3.1 File Naming

Type Convention Example
Module Directory Lowercase singular noun user/, role/, menu/
Schema File schemas.py app/system/user/schemas.py
Service File service.py app/auth/service.py
Router File router.py app/system/role/router.py
Config File config.py app/config.py
Model File Split by domain app/system/user/models.py
Constants File constants.py app/constants.py(global) / app/system/user/constants.py(domain)
Enum File enums.py / constants.py app/enums.py(global) / app/system/role/constants.py(domain enums)
Test File test_<模块>.py tests/auth/test_auth.py

3.2 Class Naming

Type Convention Example
ORM Model Sys + PascalCase SysUser, SysRole, SysMenu, SysDept
Pydantic Schema Feature + suffix UserCreate, UserUpdate, UserVO, UserQuery
Service Class Module name + Service UserService, AuthService, RoleService
Config Class Settings Settings(singleton)
Enum Class Feature name + Enum StatusEnum, DataScopeEnum
Exception BusinessException Uniformly use BusinessException

Schema Suffix Conventions:

Suffix Purpose Example
Create Create form UserCreate, RoleCreate
Update Update form UserUpdate, MenuUpdate
VO View object (return) UserVO, RoleVO, DictVO
Query Pagination query parameters UserQuery, RoleQuery, LogQuery
Form Specific operation form UserPasswordForm, RoleMenuForm
Result Response Result LoginResult, ExcelResultVO

3.3 Method Naming

Operation Method Name Example
Paginated Query get_page async def get_page(self, query: UserQuery) -> PageResult
Single Query get_by_id async def get_by_id(self, id: int) -> UserVO
Tree Query get_tree async def get_tree(self, keywords: str) -> list[MenuVO]
Dropdown Options get_options async def get_options(self) -> list[dict]
Create create async def create(self, form: UserCreate) -> UserVO
Update update async def update(self, form: UserUpdate) -> UserVO
Delete (Batch) delete async def delete(self, ids: str) -> int
Status Change update_status async def update_status(self, id: int, status: int) -> None
Import import_<资源> async def import_users(self, data: list) -> dict
Export export_<资源> async def export_users(self, query) -> list[dict]

3.4 Variable Naming

Type Convention Example
Variable snake_case user_list, role_codes
Constant UPPER_SNAKE_CASE MAX_PAGE_SIZE, ROOT_ROLE_CODE
Private Method _ prefix def _to_vo(self, m: SysUser) -> UserVO
Boolean Variable is_/has_ prefix is_root, is_deleted, has_perm
Database Field snake_case dept_id, create_time
JSON/API Field camelCase deptId, createTime, pageSize

Key Convention: ORM model fields use snake_case (corresponding to PostgreSQL column names), Schema/API fields use camelCase (corresponding to frontend JSON key names).

3.5 import Ordering

# 1. 标准库
import io
import logging

# 2. 第三方库
from fastapi import APIRouter, Depends
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from pydantic import BaseModel, Field

# 3. 项目内部(按层排序)
from app.database import get_db
from app.constants import ROOT_ROLE_CODE
from app.pagination import PageResult
from app.dependencies import require_perm
from app.exceptions import BusinessException
from app.response import Result, ResultCode
from app.user.models import SysUser
from app.user.schemas import UserCreate, UserVO

Part 4: Routing and API Specification

4.1 Route Prefix

router = APIRouter(prefix="/api/v1/users", tags=["用户管理"])
Module Prefix
Authentication /api/v1/auth
User /api/v1/users
Role /api/v1/roles
Menu /api/v1/menus
Department /api/v1/depts
Dictionary /api/v1/dict
Configuration /api/v1/configs
Notification /api/v1/notices
Log /api/v1/logs
File /api/v1/files
SSE /api/v1/sse

4.2 Standard CRUD Paths

Operation Method Path Description
Paginated List GET /api/v1/users Query parameters:pageNum/pageSize/keywords/...
Details GET /api/v1/users/{user_id} Path parameter user_id: int
Create POST /api/v1/users Body: UserCreate
Update PUT /api/v1/users/{user_id} Body: UserUpdate
Batch Delete DELETE /api/v1/users/{ids} ids comma-separated
Change Status PATCH /api/v1/users/status Body: UserStatusForm
Reset Password PATCH /api/v1/users/password Body: UserPasswordForm
Export GET /api/v1/users/export Return StreamingResponse xlsx
Import POST /api/v1/users/import UploadFile xlsx
Import Template GET /api/v1/users/template Download template xlsx
Dropdown Options GET /api/v1/roles/options Return [{value, label}]

4.3 Route Registration Order (Important!)

Fixed-path endpoints must be defined before path-parameter endpoints, otherwise /{user_id} will be matched first:

# ✅ 正确顺序
@router.get("")                    # GET /api/v1/users
@router.get("/template")           # 固定路径 —— 必须在 /{user_id} 前
@router.get("/export")             # 固定路径
@router.post("/import")            # 固定路径
@router.patch("/status")           # 固定路径
@router.patch("/password")         # 固定路径

@router.post("")                   # POST /api/v1/users
@router.get("/{user_id}")          # 路径参数 —— 最后注册
@router.put("/{user_id}")          # 路径参数
@router.delete("/{ids}")           # 路径参数

4.4 Router Function Template

# router.py — 完整模板

import io
import logging
from fastapi import APIRouter, Depends, Query, UploadFile, File
from sqlalchemy.ext.asyncio import AsyncSession
from openpyxl import Workbook

from app.database import get_db
from app.dependencies import require_perm
from app.response import Result
from app.user.schemas import UserCreate, UserQuery, UserUpdate, UserVO
from app.user.service import UserService

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/users", tags=["用户管理"])


@router.get("", summary="用户分页列表",
    dependencies=[Depends(require_perm("sys:user:list"))])
async def get_user_page(
    pageNum: int = Query(default=1, ge=1),
    pageSize: int = Query(default=10, ge=1, le=100),
    keywords: str | None = Query(default=None),
    status: int | None = Query(default=None),
    db: AsyncSession = Depends(get_db),
):
    """分页查询用户列表。

    - **pageNum**: 当前页码
    - **pageSize**: 每页条数(1-100)
    - **keywords**: 搜索关键词(用户名/昵称/手机号)
    - **status**: 状态筛选
    """
    query = UserQuery(pageNum=pageNum, pageSize=pageSize,
                      keywords=keywords, status=status)
    result = await UserService(db).get_page(query)
    return Result(data=result)


@router.get("/{user_id}", summary="用户详情",
    dependencies=[Depends(require_perm("sys:user:detail"))])
async def get_user(user_id: int, db: AsyncSession = Depends(get_db)):
    """根据 ID 获取用户详情。"""
    vo = await UserService(db).get_by_id(user_id)
    return Result(data=vo)


@router.post("", summary="创建用户",
    dependencies=[Depends(require_perm("sys:user:create"))])
async def create_user(form: UserCreate, db: AsyncSession = Depends(get_db)):
    """创建新用户,自动分配角色。"""
    vo = await UserService(db).create(form)
    return Result(data=vo)


@router.put("/{user_id}", summary="更新用户",
    dependencies=[Depends(require_perm("sys:user:edit"))])
async def update_user(user_id: int, form: UserUpdate,
                      db: AsyncSession = Depends(get_db)):
    """更新用户信息及角色。"""
    form.id = user_id
    vo = await UserService(db).update(form)
    return Result(data=vo)


@router.delete("/{ids}", summary="删除用户",
    dependencies=[Depends(require_perm("sys:user:delete"))])
async def delete_users(ids: str, db: AsyncSession = Depends(get_db)):
    """批量逻辑删除用户。"""
    count = await UserService(db).delete(ids)
    return Result(data=count, msg=f"成功删除 {count} 条记录")

Part 5: HTTP Status Codes and Business Error Codes

5.1 Design Philosophy: Dual-Track System (HTTP Semantics + Business Codes)

Background: There are two camps of debate in the community—"uniformly return 200, distinguish by the code in the body" vs "use correct HTTP status codes". This specification adopts the RFC 9457 Problem Details approach + a dual-track solution compatible with the youlai-boot/vue3-element-admin frontend interceptorDual-Track Solution。

Solution Representative Defect
Uniform 200 Some domestic projects, GraphQL Violates HTTP semantics; gateways/monitoring cannot identify errors; API tools misjudge success
Pure HTTP Status Codes RFC 9457, Zuplo best practices Cannot express fine-grained business errors (e.g., "username does not exist" vs "incorrect password" are both 401)
Dual-track system (this project) youlai-fastapi —

Dual-track system principles:

HTTP 状态码 → 大类划分(2xx 成功 / 4xx 客户端错误 / 5xx 服务端错误)
业务错误码  → 细粒度分类(A0230 Token 过期 / A0402 密码错误 / B0003 数据不存在)
  • HTTP status code: protocol layer, used by gateways/monitoring/API tools to identify request success or failure
  • Business error code: application layer, used by the frontend to precisely determine business logic
  • Coexistence of both: every error response carries both the correct HTTP status code and the code field in the body

5.2 HTTP status code usage specification

HTTP status Meaning Usage scenario Example code in body
200 Success Business operation succeeded 00000
400 Client request error Malformed request, missing parameters A0400
401 Unauthenticated Invalid/expired Token, not logged in A0230、A0231
403 No permission Authenticated but no operation permission A0301
404 Resource not found The queried data does not exist B0003
409 Conflict Unique key conflict, state conflict B0002
422 Parameter validation failed Pydantic validation failed A0400
500 Internal server error Uncaught exception, system error B0001

Why not use 4xx to represent all business errors? HTTP status codes should reflectprotocol layersuccess or failure. "Wrong password" is a business validation failure rather than a request format error; using 400 would confuse it with parameter format errors. This project classifies "wrong password" as 401 (authentication failure), "username does not exist" as 404 (resource not found), and "unique key conflict" as 409 (conflict)—choosing the status code with the closest semantics.

5.3 Business error codes (ResultCode)

from enum import Enum


class ResultCode(str, Enum):
    """业务错误码 — 与 HTTP 状态码配合使用。

    首位编码:
      0 - 成功
      A - 用户端错误(4xx)
      B - 系统端错误(5xx)
      C - 第三方服务错误(5xx)
    """

    # ── 成功 ──
    SUCCESS = "00000"                    # → HTTP 200

    # ── 认证/授权类(4xx)──
    TOKEN_INVALID = "A0230"              # → HTTP 401 访问令牌无效或过期
    TOKEN_REFRESH_FAIL = "A0231"         # → HTTP 401 刷新令牌无效或过期
    ACCESS_DENIED = "A0301"              # → HTTP 403 权限不足

    # ── 参数/校验类(4xx)──
    PARAM_VALID_FAIL = "A0400"           # → HTTP 422 参数校验失败
    USERNAME_NOT_FOUND = "A0401"         # → HTTP 404 用户名不存在
    BAD_CREDENTIALS = "A0402"            # → HTTP 401 密码错误
    USER_DISABLED = "A0403"             # → HTTP 403 用户被禁用
    CAPTCHA_ERROR = "A0404"             # → HTTP 400 验证码错误

    # ── 业务异常 ──
    SYSTEM_ERROR = "B0001"              # → HTTP 500 系统执行异常(全局兜底)
    DUPLICATE_KEY = "B0002"              # → HTTP 409 数据重复
    DATA_NOT_FOUND = "B0003"             # → HTTP 404 数据不存在
    OPERATE_DENIED = "B0004"             # → HTTP 403 操作不允许

    @property
    def http_status(self) -> int:
        """业务错误码 → 对应的 HTTP 状态码。"""
        mapping = {
            "00000": 200,
            "A0230": 401, "A0231": 401,
            "A0301": 403, "A0403": 403, "B0004": 403,
            "A0400": 422,
            "A0401": 404, "B0003": 404,
            "A0402": 401,
            "A0404": 400,
            "B0002": 409,
            "B0001": 500,
        }
        return mapping.get(self.value, 500)

5.4 BusinessException and global exception handler

# app/exceptions.py

from fastapi import Request
from fastapi.responses import JSONResponse
from app.response import ResultCode


class BusinessException(Exception):
    """业务异常 — 携带业务错误码和 HTTP 状态码。"""

    def __init__(self, code: ResultCode = ResultCode.SYSTEM_ERROR, msg: str = "系统异常"):
        self.code = code
        self.msg = msg
        self.http_status = code.http_status  # ← 自动映射 HTTP 状态码
        super().__init__(msg)


async def business_exception_handler(request: Request, exc: BusinessException) -> JSONResponse:
    """业务异常处理 — 返回语义化 HTTP 状态码 + body 中的 code。"""
    return JSONResponse(
        status_code=exc.http_status,            # ← HTTP 401/403/404/409/500...
        content={"code": exc.code.value, "msg": exc.msg, "data": None},
    )


async def validation_exception_handler(request: Request, exc) -> JSONResponse:
    """参数校验异常 — HTTP 422 + body code A0400。"""
    return JSONResponse(
        status_code=422,
        content={"code": ResultCode.PARAM_VALID_FAIL.value, "msg": str(exc), "data": None},
    )


async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """全局兜底 — HTTP 500 + body code B0001。"""
    return JSONResponse(
        status_code=500,
        content={"code": ResultCode.SYSTEM_ERROR.value, "msg": "系统执行异常", "data": None},
    )

5.5 Business exception throwing example

# ✅ 认证失败 → HTTP 401
raise BusinessException(code=ResultCode.TOKEN_INVALID, msg="访问令牌无效或过期")
raise BusinessException(code=ResultCode.BAD_CREDENTIALS, msg="密码错误")

# ✅ 权限不足 → HTTP 403
raise BusinessException(code=ResultCode.ACCESS_DENIED, msg="权限不足")

# ✅ 数据不存在 → HTTP 404
raise BusinessException(code=ResultCode.DATA_NOT_FOUND, msg="用户不存在")
raise BusinessException(code=ResultCode.USERNAME_NOT_FOUND, msg="用户名不存在")

# ✅ 唯一键冲突 → HTTP 409
raise BusinessException(code=ResultCode.DUPLICATE_KEY, msg="用户名已存在")

# ✅ 操作不允许 → HTTP 403
raise BusinessException(code=ResultCode.OPERATE_DENIED, msg="存在子菜单,无法删除")

# ✅ 系统异常 → HTTP 500(由全局异常处理器兜底,通常不手动抛出)

5.6 Compatibility with frontend axios interceptors

vue3-element-admin's axios interceptorhandles both branches, naturally compatible with the dual-track system:

// vue3-element-admin/src/utils/request.ts(已验证)
http.interceptors.response.use(
  (response) => {
    // HTTP 2xx 进入此分支
    const { code, data, msg } = response.data;
    if (code === "00000") return data;        // 业务成功
    ElMessage.error(msg);                      // 业务错误(HTTP 200 但 code 非 00000)
    return Promise.reject(new Error(msg));
  },
  (error) => {
    // HTTP 4xx/5xx 进入此分支
    const { code, msg } = error.response.data;
    if (code === "A0230") { /* Token 过期 → 自动刷新 */ }
    if (code === "A0231") { /* Refresh 失败 → 跳转登录 */ }
    if (code === "A0301") { /* 权限不足 → 刷新权限 */ }
    ElMessage.error(msg);
    return Promise.reject(error);
  }
);

Key: no matter which branch the frontend enters, it reads the business code from response.data.code The dual-track system requires no frontendchanges whatsoever。

5.7 Error code design specification

First digit Meaning HTTP category Range
0 Success 2xx 00000
A Client-side error 4xx A0001-A0999
B Server-side error 5xx B0001-B0999
C Third-party service error 5xx C0001-C0999

Second digit subcategory(Category A):

Second digit Subcategory Example
0 General A0001 unknown error
2 Authentication/Token A0230 Token expired,A0231 Refresh invalid
3 Authorization/permission A0301 insufficient permission
4 Parameter validation A0400 validation failed,A0401 user does not exist,A0402 wrong password
5 Tenant A0250 tenant must be selected

Process for adding a new error code:

  1. In ResultCode add a new value to the enum
  2. In http_status add mapping to the property's mapping
  3. Update the table in Section 5.3 of this specification

Part 6: Unified Response Format

6.1 Result Structure

{
    "code": "00000",
    "msg": "成功",
    "data": { … }
}
from pydantic import BaseModel, Field
from typing import Generic, TypeVar

T = TypeVar("T")

class Result(BaseModel, Generic[T]):
    code: str = Field(default="00000", description="业务状态码")
    msg: str = Field(default="成功", description="提示信息")
    data: T | None = Field(default=None, description="响应数据")

6.2 PageResult Structure

{
    "code": "00000",
    "msg": "成功",
    "data": {
        "list": [ … ],
        "total": 100,
        "pageNum": 1,
        "pageSize": 10
    }
}
class PageResult(BaseModel):
    list: list = Field(default_factory=list)
    total: int = Field(default=0)
    pageNum: int = Field(default=1)
    pageSize: int = Field(default=10)

6.3 Pagination Query Parameters

class PageQuery(BaseModel):
    pageNum: int = Field(default=1, ge=1)
    pageSize: int = Field(default=10, ge=1, le=100)

Frontend Convention: Pagination parameters are named pageNum / pageSize(camelCase), compatible with the TablePage component of vue3-element-admin.

6.4 Return Examples

# 成功返回
return Result(data=user_vo)

# 成功返回(自定义消息)
return Result(data=count, msg=f"成功删除 {count} 条记录")

# 成功返回(无数据)
return Result(data=None)

# 错误返回
return Result(code=ResultCode.CAPTCHA_ERROR, msg="验证码错误", data=None)

Part 7: ORM Model Specification

7.1 Base Class Mixin

from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import BigInteger, DateTime, Integer, func


class Base(DeclarativeBase):
    """ORM 声明式基类。"""
    pass


class TimestampMixin:
    """自动管理 create_time / update_time。"""
    create_time: Mapped[datetime | None] = mapped_column(
        DateTime, server_default=func.now(), comment="创建时间"
    )
    update_time: Mapped[datetime | None] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now(), comment="更新时间"
    )


class SoftDeleteMixin:
    """逻辑删除标识。"""
    is_deleted: Mapped[int] = mapped_column(
        Integer, default=0, server_default="0", comment="逻辑删除 0-未删除 1-已删除"
    )


class BaseIdMixin:
    """自增主键 ID。"""
    id: Mapped[int] = mapped_column(
        BigInteger, primary_key=True, autoincrement=True, comment="主键ID"
    )

7.2 ORM Model Example

class SysUser(Base, BaseIdMixin, TimestampMixin, SoftDeleteMixin):
    __tablename__ = "sys_user"

    username: Mapped[str] = mapped_column(String(64), unique=True, comment="用户名")
    nickname: Mapped[str] = mapped_column(String(64), comment="昵称")
    password: Mapped[str] = mapped_column(String(100), comment="密码")
    dept_id: Mapped[int | None] = mapped_column(BigInteger, comment="部门ID")
    mobile: Mapped[str | None] = mapped_column(String(20), comment="手机号")
    email: Mapped[str | None] = mapped_column(String(100), comment="邮箱")
    status: Mapped[int] = mapped_column(Integer, default=1, server_default="1",
                                         comment="状态 1-启用 0-禁用")

7.3 Field Naming Comparison

SQL Column Name ORM Field Schema Field Description
dept_id dept_id deptId Department ID
create_time create_time createTime Creation Time
is_deleted is_deleted — Logical Delete (internal use)
parent_id parent_id parentId Parent Node ID

Conversion Rule: When ORM → VO,to_vo or _to_vo method is responsible for snake_case → camelCase conversion.

7.4 VO Conversion Template

@staticmethod
def _to_vo(m: SysUser) -> UserVO:
    """ORM 模型 → 视图对象(snake_case → camelCase)。"""
    return UserVO(
        id=m.id,
        username=m.username,
        deptId=m.dept_id,       # ← 手动映射
        createTime=str(m.create_time) if m.create_time else None,
        # ...
    )

Part 8: Authentication and Authorization

8.1 Token Mode

Switch via the SESSION_TYPE environment variable:

Value Mode TokenManager
jwt(default) JWT self-contained Token JwtTokenManager
redis-token Redis-stored Token RedisTokenManager

8.2 Get Current User

from app.dependencies import get_current_user

@router.get("/me")
async def my_info(user: SysUserDetails = Depends(get_current_user)):
    return Result(data={"userId": user.userId, "username": user.username})

8.3 Permission Verification

from app.dependencies import require_perm

# 精确权限
@router.post("", dependencies=[Depends(require_perm("sys:user:create"))])
async def create_user(form: UserCreate, db: AsyncSession = Depends(get_db)):
    ...

# 登录即可(不检查权限)
@router.get("/options", dependencies=[Depends(require_perm())])
async def get_options(db: AsyncSession = Depends(get_db)):
    ...

8.4 Permission Identifier Naming Convention

模块:实体:操作
sys:user:create
sys:user:edit
sys:user:delete
sys:role:list
sys:menu:list
sys:dept:list
Operation Description
list List/Query
detail Details
create Create
edit Edit
delete Delete
import Import
export Export
reset-pwd Reset Password
assign-menu Assign Menu Permissions

Part 9: Database Operation Specification

9.1 Asynchronous Query

# ✅ 正确:使用 async/await
result = await self.db.execute(
    select(SysUser).where(SysUser.id == user_id, SysUser.is_deleted == 0)
)
user = result.scalar_one_or_none()

# ✅ 正确:分页查询
rows = await self.db.execute(
    select(SysUser)
    .where(*conditions)
    .order_by(SysUser.create_time.desc())
    .offset(offset)
    .limit(page_size)
)
users = rows.scalars().all()

# ✅ 正确:原生 SQL(复杂联表查询)
result = await self.db.execute(
    text("""
        SELECT r.code FROM sys_role r
        INNER JOIN sys_user_role ur ON r.id = ur.role_id
        WHERE ur.user_id = :user_id AND r.is_deleted = 0 AND r.status = 1
    """),
    {"user_id": user_id},
)

9.2 Transaction Management

# 由 get_db() 依赖自动管理:
# yield 前 → session 开始
# yield 后 → commit(成功)或 rollback(异常)
# finally → session.close()

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()     # 自动提交
        except Exception:
            await session.rollback()   # 自动回滚
            raise
        finally:
            await session.close()

9.3 Batch Operations

# ✅ 批量删除(原生 SQL)
await self.db.execute(
    text("UPDATE sys_user SET is_deleted = 1 WHERE id = ANY(:ids)"),
    {"ids": id_list},
)

# ✅ 批量插入
for data in batch:
    self.db.add(SysConfig(**data))
await self.db.flush()

Part 10: Adding a New Module — Complete Tutorial

Using the addition of the "Data Dictionary Item" module as an example, demonstrating the steps from scratch to completion.

Step 1: Check the ORM Model

Confirm that app/system/dict/models.py already has the corresponding ORM model. If not, create:

# app/system/dict/models.py
class SysDictItem(Base, BaseIdMixin):
    __tablename__ = "sys_dict_item"
    dict_code: Mapped[str | None] = mapped_column(String(50))
    value: Mapped[str | None] = mapped_column(String(50))
    label: Mapped[str | None] = mapped_column(String(100))
    tag_type: Mapped[str | None] = mapped_column(String(50))
    status: Mapped[int] = mapped_column(Integer, default=1)
    sort: Mapped[int] = mapped_column(Integer, default=0)

Step 2: Create the Module Directory

mkdir app/dict_item

Step 3: Create schemas.py

# app/dict_item/schemas.py
"""字典项 Schemas。"""
from pydantic import BaseModel, Field


class DictItemCreate(BaseModel):
    """创建字典项表单。"""
    dictCode: str = Field(..., max_length=50, description="关联字典编码")
    value: str = Field(..., max_length=50, description="字典项值")
    label: str = Field(..., max_length=100, description="字典项标签")
    tagType: str | None = Field(default=None, max_length=50, description="标签类型")
    status: int = Field(default=1, description="状态 1-正常 0-禁用")
    sort: int = Field(default=0, description="排序")


class DictItemUpdate(DictItemCreate):
    """更新字典项表单。"""
    id: int = Field(..., description="字典项ID")


class DictItemVO(BaseModel):
    """字典项视图对象。"""
    id: int | None = None
    dictCode: str = ""
    value: str = ""
    label: str = ""
    tagType: str | None = None
    status: int = 1
    sort: int = 0
    model_config = {"from_attributes": True}


class DictItemQuery(BaseModel):
    """字典项查询参数。"""
    dictCode: str = Field(..., description="字典编码")

Step 4: Create service.py

# app/dict_item/service.py
"""字典项服务。"""
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.exceptions import BusinessException
from app.response import ResultCode
from app.dict.models import SysDictItem
from app.dict_item.schemas import (
    DictItemCreate, DictItemUpdate, DictItemVO, DictItemQuery,
)


class DictItemService:
    """字典项管理服务。"""

    def __init__(self, db: AsyncSession):
        self.db = db

    async def get_items(self, dict_code: str) -> list[DictItemVO]:
        """根据字典编码查询字典项列表。"""
        rows = await self.db.execute(
            select(SysDictItem)
            .where(SysDictItem.dict_code == dict_code)
            .order_by(SysDictItem.sort.asc())
        )
        items = rows.scalars().all()
        return [DictItemVO.model_validate(it, from_attributes=True) for it in items]

    async def get_by_id(self, item_id: int) -> DictItemVO:
        """根据 ID 查询字典项。"""
        obj = await self.db.get(SysDictItem, item_id)
        if obj is None:
            raise BusinessException(code=ResultCode.DATA_NOT_FOUND, msg="字典项不存在")
        return DictItemVO.model_validate(obj, from_attributes=True)

    async def create(self, form: DictItemCreate) -> DictItemVO:
        """创建字典项。"""
        obj = SysDictItem(**form.model_dump())
        self.db.add(obj)
        await self.db.flush()
        return DictItemVO.model_validate(obj, from_attributes=True)

    async def update(self, form: DictItemUpdate) -> DictItemVO:
        """更新字典项。"""
        obj = await self.db.get(SysDictItem, form.id)
        if obj is None:
            raise BusinessException(code=ResultCode.DATA_NOT_FOUND, msg="字典项不存在")
        for key, val in form.model_dump(exclude={"id"}).items():
            setattr(obj, key, val)
        await self.db.flush()
        return DictItemVO.model_validate(obj, from_attributes=True)

    async def delete(self, ids: str) -> int:
        """批量删除字典项。"""
        id_list = [int(x) for x in ids.split(",") if x.strip()]
        for iid in id_list:
            obj = await self.db.get(SysDictItem, iid)
            if obj:
                await self.db.delete(obj)
        await self.db.flush()
        return len(id_list)

Step 5: Create router.py

# app/dict_item/router.py
"""字典项路由。"""
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
from app.dependencies import require_perm
from app.response import Result
from app.dict_item.schemas import (
    DictItemCreate, DictItemUpdate,
)
from app.dict_item.service import DictItemService

router = APIRouter(prefix="/api/v1/dict/items", tags=["字典管理"])


@router.get("/{dict_code}", summary="字典项列表")
async def get_dict_items(dict_code: str, db: AsyncSession = Depends(get_db)):
    items = await DictItemService(db).get_items(dict_code)
    return Result(data=items)


@router.get("/{item_id}/detail", summary="字典项详情")
async def get_dict_item(item_id: int, db: AsyncSession = Depends(get_db)):
    vo = await DictItemService(db).get_by_id(item_id)
    return Result(data=vo)


@router.post("", summary="创建字典项",
    dependencies=[Depends(require_perm("sys:dict:create"))])
async def create_dict_item(form: DictItemCreate,
    db: AsyncSession = Depends(get_db)):
    vo = await DictItemService(db).create(form)
    return Result(data=vo)


@router.put("/{item_id}", summary="更新字典项",
    dependencies=[Depends(require_perm("sys:dict:edit"))])
async def update_dict_item(item_id: int, form: DictItemUpdate,
    db: AsyncSession = Depends(get_db)):
    form.id = item_id
    vo = await DictItemService(db).update(form)
    return Result(data=vo)


@router.delete("/{ids}", summary="删除字典项",
    dependencies=[Depends(require_perm("sys:dict:delete"))])
async def delete_dict_items(ids: str, db: AsyncSession = Depends(get_db)):
    count = await DictItemService(db).delete(ids)
    return Result(data=count)

Step 6: Create __init__.py

# app/dict_item/__init__.py

Step 7: In main.py register the route

# app/main.py — create_app() 函数中追加
from app.dict_item.router import router as dict_item_router
app.include_router(dict_item_router)

Step 8: Verify

# 启动服务
fastapi dev app/main.py

# 访问 Swagger 确认路由已注册
open http://localhost:8000/api/v1/swagger-ui.html

Module File List

app/dict_item/
├── __init__.py
├── schemas.py       # ← 第一步创建
├── service.py       # ← 第二步创建
└── router.py        # ← 第三步创建

Extension: Single-File Module (Simple CRUD)

For simple modules such as log management, schemas + service + router can be merged into a single file:

# app/system/log/router.py
# ┌── schemas ──┐
class LogQuery(BaseModel): ...
class LogVO(BaseModel): ...

# ┌── service ──┐
class LogService: ...
    async def get_page(self, query): ...

# ┌── router ──┐
router = APIRouter(prefix="/api/v1/logs", tags=["日志管理"])

@router.get("", ...)
async def get_logs(...): ...

Selection Criteria: Single entity < 5 endpoints → single-file module; > 5 endpoints or complex queries → split into schemas + service + router.


Part 11: Comment Specification

Source:PEP 257 (Docstring Conventions) + Google Style Docstrings。

11.1 General Principles

  • docstring first: All public modules, classes, and functions must have docstrings
  • Self-explanatory code: Good naming and structure are self-explanatory; comments describe "why" rather than "how"
  • Chinese first: Rather than using half-baked English, it is better to explain the problem clearly in Chinese; keep proper nouns in English (such as HTTP、async)
  • Keep in sync: when code is modified, the docstring must be modified accordingly

11.2 docstring format (Google style)

async def get_user_page(
    pageNum: int = Query(default=1, ge=1),
    pageSize: int = Query(default=10, ge=1, le=100),
    keywords: str | None = Query(default=None),
    db: AsyncSession = Depends(get_db),
) -> PageResult:
    """分页查询用户列表。

    根据关键词模糊搜索用户名/昵称/手机号,支持状态筛选。

    Args:
        pageNum: 当前页码,从 1 开始。
        pageSize: 每页条数,1-100。
        keywords: 搜索关键词(用户名/昵称/手机号),为空时查全部。
        db: 异步数据库会话。

    Returns:
        分页结果,包含 list 和 total。

    Raises:
        BusinessException: 当 pageSize 超过 100 时(通常由 Pydantic 校验拦截)。
    """
    ...

11.3 Key points for comments at each layer

Layer Must explain Example
Module (file header) File responsibility """字典项路由。"""
Class Responsibility, key dependencies """字典项管理服务,依赖 AsyncSession。"""
Public method Function, parameters, return value, exceptions See 11.2
Private method (_ prefix) A brief explanation is sufficient """ORM 模型 → 视图对象。"""

11.4 Common anti-patterns

Anti-pattern Problem Correct approach
def get_user(id): pass No docstring Public method has no documentation Add a docstring
"""获取用户""" Parameters have no explanation Missing Args/Returns Add complete Args/Returns/Raises
docstring is inconsistent with the code Misleads maintainers Update in sync when the code changes
Commented-out code blocks are kept Historical code can be checked from Git Delete directly
# TODO fix this No assignee, no time # TODO(zhangsan, 2025/06/01, 下版本修复)

11.5 TODO / FIXME marker conventions

Marker Purpose Format Example
TODO To be implemented TODO(标记人, 日期, [说明]) TODO(zhangsan, 2025/06/01, 扩展邮箱验证码)
FIXME Known bug FIXME(标记人, 日期, [说明]) FIXME(lisi, 2025/06/15, 并发场景偶发死锁)

Part 12: Code quality checklist

11.1 General checks

  • All public classes and methods have docstrings
  • Use Pydantic v2 of model_dump() instead of dict()
  • Use model_validate(obj, from_attributes=True) for ORM → Schema conversion
  • All .py files have # -*- coding: utf-8 -*- or UTF-8 encoding
  • imports are ordered as standard library → third-party → internal
  • No unused imports
  • No print() debug code; uniformly use logger
  • Logs do not output sensitive information such as passwords and keys
  • Configuration is managed through Settings + .env , not hardcoded
  • All async def functions internally use await

11.2 Database-related

  • ORM model field names use snake_case, consistent with database column names
  • All queries add is_deleted == 0 filtering (if the model has SoftDeleteMixin)
  • Use select instead of Model.query(SQLAlchemy 2.0+ style)
  • For large data operations, use flush() instead of frequent commit()
  • ScalarResult.scalar_one_or_none() instead of first()(distinguish None vs the first record)

11.3 API-related

  • Route prefix uniformly "/api/v1/模块名"
  • Fixed-path endpoints are defined before path-parameter endpoints
  • Pagination parameters are named pageNum / pageSize
  • JSON fields use camelCase (deptId、createTime)
  • Uniformly return Result[T] wrapper (body contains code/msg/data)
  • HTTP status code semantics: success 200 / authentication failure 401 / insufficient permissions 403 / not found 404 / conflict 409 / validation 422 / system error 500
  • Business error codes work in tandem with HTTP status codes (see Part 5)
  • ResultCode.http_status property mapping is correct
  • Error returns use the ResultCode enum, no hardcoded strings
  • Sensitive endpoints add dependencies=[Depends(require_perm(...))]
  • tree_path is set after add + flush (once the auto-increment id is obtained)

11.4 Service layer

  • The Service constructor accepts db: AsyncSession
  • Throw when data does not exist BusinessException(code=ResultCode.DATA_NOT_FOUND)
  • Throw on unique key conflict BusinessException(code=ResultCode.DUPLICATE_KEY)
  • Throw when the operation is not allowed BusinessException(code=ResultCode.OPERATE_DENIED)
  • Check that parameters are non-empty before batch operations
  • _to_vo / _to_tree and other private method prefixes _

Part 13: Common anti-patterns

Anti-pattern Problem Correct approach
print("debug") No log level, no timestamp logger.info() / logger.debug()
result.scalars().first() Does not distinguish None vs the first record result.scalar_one_or_none()
model.dict() Deprecated in Pydantic v2 model.model_dump()
Hardcoded configuration Inconvenient for operations Use Settings + .env
db.execute() not after await Async not executed await self.db.execute(...)
flush fetch before obj.id Auto-increment id not yet generated First flush() then fetch id
SQL query missing is_deleted = 0 Queries already-deleted data Add logical delete conditions to all queries
Fixed path after /{id} after Intercepted by path parameter first Register fixed paths first
Duplicate import of the same module Unnecessary Merge into a single import
try/except catch all exceptions then pass Hides errors Only catch known exceptions, log them
All errors uniformly return HTTP 200 Gateway/monitoring cannot identify errors; violates HTTP semantics HTTP status code semantics + in the body code dual-track system (Part 5)
Business errors hardcode HTTP status codes Such as JSONResponse(status_code=401) scattered everywhere Use ResultCode.http_status property for unified mapping
String hardcoded business codes Such as code="A0230" Use ResultCode.TOKEN_INVALID.value enum

Part 14: Single-module file

For config、notice、log and other simple modules, schemas + service + router can be merged into a single router.py file, reducing file fragmentation.


Part 15: Docker deployment

# docker/docker-compose.yml
services:
  api:
    build: ..
    ports: ["8000:8000"]
    depends_on: [postgres, redis]
    environment:
      DATABASE_URL: postgresql+asyncpg://postgres:123456@postgres:5432/youlai_admin
      REDIS_URL: redis://redis:6379/0
    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4

  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_DB: youlai_admin
      POSTGRES_PASSWORD: 123456
    ports: ["5432:5432"]

  redis:
    image: redis:7-alpine
    ports: ["6379:6379"]
# 启动
docker-compose -f docker/docker-compose.yml up -d