FastAPI 请求和响应
分别验证查询、路径、请求体、请求头和 Cookie,再观察响应状态、重定向与自定义响应头。
学完这一章,你能够
- 分别验证查询、路径、请求体、请求头和 Cookie,再观察响应状态、重定向与自定义响应头。
HTTP 请求从哪里取值
HTTP 请求包括方法、目标、请求头和可选请求体。GET /observations 声明 skip=0、limit=10。传 ?skip=1&limit=5 后得到两个整数。非整数查询会返回 422,loc 指向 query。
路径中的 /observations/42 由整数 sample_id 接收。URL 查询中的 q 可单独传入,省略 q 不影响路径匹配。服务按路径模板和方法选择路由,再做参数校验。
JSON 请求体和模型响应
POST /observations 使用 Observation 接收 JSON。name 和 price 必填,description 与 tax 可省略。当前模型可将数字字符串转成浮点值,不可解析的价格返回 422。
同步路由返回普通字典时,FastAPI 生成 application/json。返回 Pydantic 模型也会序列化为 JSON。本站用 Swagger UI 填写一份采样记录并点击 Execute,观察实际状态、价格和默认空值。
用 response_model 约束输出字段。本站第二个 POST 接收合成的私有备注,只返回公开字段。真实凭据还需在日志、异常和数据存储等位置单独保护。
请求头与 Cookie
Header() 从请求头读取。默认把 Python 参数 client_tag 的下划线转换为请求头中的连字符。Cookie() 从 Cookie 头解析 view_mode。可选字段无输入时都为 None。
实验使用固定无敏感值 Client-Tag: bench 与 view_mode=compact。应用需要身份校验时,不应把会话令牌直接回显到响应或日志。
重定向、错误和附加响应头
GET /jump 返回 RedirectResponse,状态 307 和 Location /observations。客户端若选择跟随,才会发送下一次请求。末尾斜杠匹配也可能自动重定向,应与应用显式返回区分。
GET /look-up/7 通过 HTTPException 得到 404 和 detail。GET /look-up/42 进入正常分支。路径类型错误产生的 422 是另一类结果。
GET /with-header 直接返回 JSONResponse,并附 X-Lab-Result 响应头。直接构建响应时,应用需自行控制媒体类型、序列化和响应契约。
检查真实 POST、重定向、Cookie 和响应头
展开查看收起
"""蓝色天空网 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()}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
完整开发工程
解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
200 属于最终请求。查看禁用跟随后首个响应的状态和 Location,或查看客户端记录的响应链。