全书目录

第二篇:FastAPI 完全指南 —— 软件城市政务大厅宇宙

第五章:路径参数和查询参数 —— 门牌号与附加说明

1 分钟 176 字 第 51 / 962 个阅读单元

假设软件城市里有“通行证中心”,我们先做两个最常见的输入来源:

  • 路径参数:办哪一张证
  • 查询参数:查的时候带什么筛选条件
py
from fastapi import FastAPI

app = FastAPI()

fake_db = [
    {"id": 1, "owner": "Ada", "status": "pending"},
    {"id": 2, "owner": "Linus", "status": "approved"},
    {"id": 3, "owner": "Grace", "status": "rejected"},
]

@app.get("/permits/{permit_id}")
async def get_permit(permit_id: int, verbose: bool = False):
    return {"permit_id": permit_id, "verbose": verbose}

@app.get("/permits/")
async def list_permits(skip: int = 0, limit: int = 10, status: str | None = None):
    rows = fake_db[skip : skip + limit]
    if status is not None:
        rows = [row for row in rows if row["status"] == status]
    return rows

FastAPI 的判断规则非常关键:

text
函数签名里的参数
│
├── 名字出现在路径里      -> 路径参数
├── 是 Pydantic 模型      -> 请求体
└── 其他普通参数          -> 默认当查询参数

如果你把 permit_id 声明成 int,结果用户传了 "abc",FastAPI 不会让脏数据溜进业务代码。

这就是它的核心体验之一:

同一个类型标注,既是编辑器提示,又是运行时校验规则。