from typing import Annotated
from fastapi import APIRouter, Query
routes = APIRouter(tags=["query"])
@routes.get("/filters/basic")
def basic(q: Annotated[str | None, Query(max_length=12)] = None):
return {"q": q}
@routes.get("/filters/code")
def code(q: Annotated[str | None, Query(min_length=3, max_length=12, pattern=r"^bay-[a-z]+$")] = None):
return {"q": q}
@routes.get("/filters/default")
def default(q: Annotated[str, Query(min_length=3)] = "bay-north"):
return {"q": q}
@routes.get("/filters/required")
def required(q: Annotated[str, Query(min_length=3)]):
return {"q": q}
@routes.get("/filters/required-nullable")
def required_nullable(q: Annotated[str | None, Query(min_length=3)]):
return {"q": q}
@routes.get("/filters/tags")
def tags(q: Annotated[list[str] | None, Query()] = None):
return {"q": q}
@routes.post("/filters/list-body")
def list_body(q: list[str]):
return {"q": q}
@routes.get("/filters/label")
def label(label: Annotated[str | None, Query(
alias="label-query", title="记录标签", description="用于筛选现场记录",
min_length=3, max_length=12, deprecated=True,
)] = None):
return {"label": label}
@routes.get("/filters/internal")
def internal(hint: Annotated[str | None, Query(include_in_schema=False)] = None):
return {"hint": hint}
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
入口文件:projects/fastapi-request-validation-lab/query_rules.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
query_rules.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a507.zip
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip