FastAPI 基本路由与路径匹配
从同步根路由开始,观察整数路径参数和可选查询参数的不同来源。
学完这一章,你能够
- 从同步根路由开始,观察整数路径参数和可选查询参数的不同来源。
路由如何选中函数
FastAPI() 创建应用。@app.get("/") 注册根路径上的 GET。请求到达时先匹配 HTTP 方法和路径,再运行关联的函数。同步 def 路由可以直接返回一个字典,由框架生成 JSON 响应。
解压工程后运行 python -m uvicorn main:app --host 127.0.0.1 --port 8000。冒号左边是模块,右边是应用对象。开发用的 --reload 另行启用。先请求 GET /,确认应用确实返回就绪信息。
路径占位符与可选查询
GET /observations/42 匹配 /observations/{sample_id},并按注解将 42 转为整数。GET /observations/no 无法转换,返回 422,detail.loc 指向 path、sample_id。
q: str | None = None 声明可省略的查询参数。省略 q 时得到 None,显式写 ?q= 得到空字符串,写 ?q=north 则得到 north。旧式 str = None 能表达默认值,却无法在类型注解中说明可能得到 None。
从规范核对路由
查看 /openapi.json 中的 /observations/{sample_id},可看到 sample_id 位于 path 且必填,q 位于 query 且可省略。/docs 可用表单发请求。本站从浏览器实际访问了根路径和带参数的路由。
运行同步路由并比较查询参数
"""蓝色天空网 FastAPI 请求与响应实验。"""
from pathlib import Path
from typing import Annotated
from fastapi import Cookie, FastAPI, Header, HTTPException, Query
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from models import Observation, StationInput, StationOutput
app = FastAPI(title="蓝色天空网请求实验", docs_url=None)
app.mount("/docs-assets", StaticFiles(directory=Path(__file__).with_name("vendor")), name="docs-assets")
@app.get("/docs", include_in_schema=False)
def docs():
return get_swagger_ui_html(
openapi_url="/openapi.json", title=app.title,
swagger_js_url="/docs-assets/swagger-ui-bundle.js",
swagger_css_url="/docs-assets/swagger-ui.css",
swagger_favicon_url="data:,", swagger_ui_parameters={"validatorUrl": None},
)
@app.get("/", operation_id="read_status")
def status():
return {"service": "observations", "ready": True}
@app.get("/observations")
def listing(skip: Annotated[int, Query(ge=0)] = 0, limit: Annotated[int, Query(ge=1, le=50)] = 10):
return {"skip": skip, "limit": limit}
@app.get("/observations/{sample_id}")
def read_sample(sample_id: int, q: str | None = None):
return {"sample_id": sample_id, "q": q}
@app.post("/observations", operation_id="submit_observation")
def create(sample: Observation) -> Observation:
return sample
@app.get("/context")
def context(client_tag: Annotated[str | None, Header()] = None,
view_mode: Annotated[str | None, Cookie()] = None):
return {"client_tag": client_tag, "view_mode": view_mode}
@app.get("/jump")
def jump():
return RedirectResponse(url="/observations", status_code=307)
@app.get("/look-up/{sample_id}")
def look_up(sample_id: int):
if sample_id != 42:
raise HTTPException(status_code=404, detail="sample missing")
return {"sample_id": sample_id}
@app.get("/with-header")
def with_header():
return JSONResponse({"sample_id": 42}, headers={"X-Lab-Result": "verified"})
@app.post("/stations", response_model=StationOutput)
def create_station(station: StationInput):
return {"id": 1, **station.model_dump()}
- 根路径返回就绪状态。整数路径可匹配。省略 q、传空字符串和传 north 会得到不同结果。
所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
当前源码 SHA256:e2efc6fad9d5820d9c8f72bf4fb1782b7c61b0afe843188f541626d54a6aae67
完整开发工程
解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。
所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0
ZIP SHA256:1f4e0b1fb8cd3b6a8109930de96db2ee5afe1876577db4626f7929e113b69630
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
省略 q 和写 q= 产生什么差别?
展开参考解答
省略使用 None,q= 提供了长度为零的字符串。