蓝色天空网mbsky.com · 知识 · 实践 · 创造FastAPI · 本地阅读预览
教程 / Python / 数据科学 / FastAPI

FastAPI 请求和响应

分别验证查询、路径、请求体、请求头和 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,观察实际状态、价格和默认空值。

Swagger UI 实际提交 JSON 后返回状态 200 与采样字段
本站实验截图。价格为数值,两个省略的可空字段返回 null。

用 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 和响应头

python · 阅读源码
"""蓝色天空网 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()}
预期结果 · 待实际运行核验
  • Swagger UI 的 POST 返回模型字段。独立测试观察到默认查询、307、404、422、自定义响应头以及未返回私有字段。
检查真实 POST、重定向、Cookie 和响应头

所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0

当前源码 SHA256:e2efc6fad9d5820d9c8f72bf4fb1782b7c61b0afe843188f541626d54a6aae67

下载本站示例源码

完整开发工程

解压后按 README 选择依赖。完整工程包含路由、数据模型、测试、文档资源和启动配置。

下载本站 FastAPI 实验工程

所需环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0

ZIP SHA256:1f4e0b1fb8cd3b6a8109930de96db2ee5afe1876577db4626f7929e113b69630

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么只看跟随重定向后的 200 无法判断是否发生跳转?

展开参考解答

200 属于最终请求。查看禁用跟随后首个响应的状态和 Location,或查看客户端记录的响应链。

规范与官方依据