FastAPI Response Model

本篇文章介绍 FastAPI 的返回类型 response model 可以在返回函数的类型注解中声明该接口的响应数据类型 类型注解的用法和输入数据参数一样, 可以使用: Pydantic 模型 list 列表 dict 字典 scalar 标量值 (int, bool …) @app.post("/items/") async def create_item(item: Item) -> Item: ... @app.get("/items/") async def read_items() -> list[Item]: ... FastAPI 会使用返回类型完成一下事情: 验证返回类型 如果返回的数据无效, 说明业务代码有问题, FastAPI 会返回服务器错误, 而不是把数据发给客户端 在 OpenAPI 中为响应添加 JSON Schema 用于自动生成接口文档, 自动生成客户端代码 最重要的是 它会限制并过滤出数据, 只保留返回类型中定义的字段 response_model Parameter 有时候可能需要返回的数据和类型注解不完全一致, 例如: 可能想返回字典或数据库对象, 但声明的响应类型为 Pydantic 模型 这样 Pydantic 会做数据文档、验证等工作, 即使返回的是字典或 ORM 对象 如果直接用返回类型注解, 编辑器会提示类型不匹配的错误 这种情况下, 可以用路径装饰器的 response_model 参数来声明响应类型, 而不是用返回类型注解 class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: list[str] = [] @app.post("/items/", response_model=Item) async def create_item(item: Item) -> Any: return item @app.get("/items/", response_model=list[Item]) async def read_items() -> Any: return [ {"name": "Portal Gun", "price": 42.0}, {"name": "Plumbus", "price": 32.0}, ] 注意: ...

August 12, 2025 · 5 min · 918 words · Starslayerx

Fastapi Cookie and Header Parameters

这篇文章介绍 Fastapi 的 Cookie 和 Header 参数 Cookie Parameters 通过定义 Query 和 Path 参数一样定义 Cookie 参数 from typing Annotated from fastapi import Cookie, FastAPI app = FastAPI() @app.get("/items/") async def read_items(ads_id: Annotated[str | None, Cookie()] = None): return {"ads_id": ads_id} Cookie Parameters Models 如果有一组相关的 cookies, 可以使用 Pydantic model 来声明. 这样可以在多个部分复用这个模型, 同时还能一次性为所有参数声明验证规则和元数据. 下面使用 Pydantic 模型定义 Cookies, 然后将参数声明为 Cookie from typing import Annotated from fastapi import FastAPI, Cookie from pydantic import BaseModel app = FastAPI() class Cookie(BaseModel): session_id: str fatebook_tracker: str | None = None googall_tracker: str | None = None @app.get("/items/") async def read_items(cookies: Annotated[Cookies, Cookie()]): return cookies Forbid Extra Cookies 禁止额外的Cookie 在某些场景下(虽然并不常见), 可能希望限制 API 只能接收特定的 Cookie. 这样, API 就可以"自己"管理 Cookie 同意策略了. from typing import Annotated from fastapi import FastAPI, Cookie from pydantic import BaseModel app = FastAPI() class Cookies(BaseModel): model_config = {"extra": "forbid"} # forbid extra cookies session_id: str fatebook_tracker: str | None = None googall_tracker: str | None = None @app.get("/items/") async def read_items(cookies: Annotated[Cookies, Cookie()]): return cookies 这样, 如果客户端发送额外的 cookies, 则会收到一个错误响应. 例如, 客户端发送了 santa_tracker 这个额外 Cookie ...

August 11, 2025 · 3 min · 499 words · Starslayerx

FastAPI Body Advanced Uses

本篇文章介绍 FastAPI Request Body 的进阶用法 Body - Multiple Parameters 首先, 可以将Path, Query 和 request body 参数声明自由的写在一起 对于 request body 参数可以是可选的, 并且可设置为默认的 None from typing import Annotated from fastapi import FastAPI, Path from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None @app.put("/items/{item_id}") async def update_item( item_id: Annotated[int, Path(title="The ID of the item to get", ge=0, le=1000)], # Path q: str | None = None, # Query item: Item | None = None, # body ): results = {"item_id": item_id} if q: results.update({"q": q}) if item: results.update({"item": item}) return results Multiple body parameters 多参数请求体 在上面例子中, FastAPI 期望一个包含 Item 属性的 JSON body, 例如 { "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2 } 但也可以声明多个body parameters, 例如 item 和 user ...

August 9, 2025 · 5 min · 911 words · Starslayerx

FastAPI Parameters and Validations

这篇文章介绍 FastAPI 中的参数验证功能 Query Parameters and String Validations FastAPI 允许为参数声明额外的信息和验证规则 from fastapi import FastAPI app = FastAPI() @app.get("/items/") async def read_items(q: str | None = None): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results q 是类型为 str | None 的查询参数, 这意味着它可以是字符串, 也可以是 None. 其默认值是 None, 因此 FastAPI 会识别它为“可选参数” FastAPI 通过 = None 的默认值知道该参数是非必填的 使用 str | None 还能帮助编辑器提供更好的类型提示和错误检测 Additional validation 额外验证 即使 q 是可选的, 但仍然可以设置条件: 如果提供了 q, 则长度不能超过50个字符 使用 Query 和 Annotated 来实现 from typing import Annotated from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Annotated[str | None, Query(max_length=50)] = None): results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]} if q: results.update({"q": q}) return results 使用 Annotated 包装后, 就可以传递额外的元数据(Query(max_length=5)), 用于校验或者文档 ...

August 7, 2025 · 4 min · 779 words · Starslayerx

FastAPI Parameters

FastAPI 是一个现代、快速(高性能)的 Python Web 框架, 它自动处理参数的解析、验证和文档生成 本文将介绍 FastAPI 中三类最常用的参数: 路径参数 (Path Parameters)、查询参数 (Query Parameters) 和 请求体(Request Body) 的用法与原理 1. Path Parameters 路径参数 路径参数是 URL 路径中的动态部分, 使用 {} 包裹表示 from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: str): return {"item_id": item_id} 访问 /items/foo 返回: {"item_id": "foo"} Data conversion & validation 类型声明与自动转换 可以为路径参数声明类型, FastAPI 会自动解析并验证: @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} 访问 /items/3, item_id 会被转换为 int 类型 Routing orders 路由匹配顺序 路径匹配按声明顺序执行, 例如 @app.get("/users/me") async def read_user_me(): return {"user_id": "current_user"} @app.get("/users/{user_id}") async def read_user(user_id: str): return {"user_id": user_id} 必须先声明 /users/me, 否则会被 /users/{user_id} 捕获 ...

August 6, 2025 · 3 min · 525 words · Starslayerx

How FastAPI Works

FastAPI 的工作原理: 从 routing 到 lifecycle 以及在现实中的使用 FastAPI FastAPI 是一个现代的 Python Web 框架, 注重高性能和开发效率. 旨在帮助开发者编写结构清晰、可靠的API, 同时尽量减少样板代码 (boilerplate) 其由以下两个库驱动: Starlette: 负责 Web 服务器逻辑、路由、中间件和异步能力 Pydantic: 基于 Python 类型提示, 处理数据验证、解析和序列化 此外, Fastapi 还有输入验证、基于 Swagger UI 的自动文档生成和代码清晰化的基础 API 请求周期 Fastapi 的请求生命周期如下 客户端请求 (Client Request) ↓ FastAPI App ↓ 中间件(Middleware) ↓ 路由匹配 (Route Matching) ↓ 依赖注入(Dependency Injection) ↓ 输入验证 (Input Validation) ↓ 端点函数 (Endpoint) ↓ 响应序列化 (Response Serialization) ↓ 客户端响应 (Client Response) 请求首先进入 FastAPI 应用 (本质就是一个 Starlette 应用) 所有中间件优先执行 (如: 日志、错误处理、CORS等) 路由器检查路径和方法, 找到对应的处理函数 FastAPI 使用Depends解析依赖 使用 Pydantic 自动解析并验证输入数据 执行端点函数, 参数验证完毕 返回结果被序列化为合适的响应格式 (JSON) 响应返回给客户端 路由 Router 在应用对象上定义 适合小项目或原型验证 ...

August 3, 2025 · 2 min · 322 words · Starslayerx

Dive into DeepLearning - 02 - Preliminaries

Course Note: d2l-video-05 - 线性代数 Jupyter Notebook: chapter_preliminaries/linear-algebra.ipynb 预备知识中 Liner Algebra 的部分 线性代数 Scalars 标量: 指只有一个元素的张量 tensors import torch x = torch.tensor(3.0) # scalar y = torch.tensor(2.0) Vectors 向量: 可以视作标量构成的列表 x = torch.arange(4) x[3] # 通过张量索引访问任一元素 len(x) # 访问张量长度 x.shape # torch.Size([4]) 只有一个轴的张量, 形状只有一个元素 Matrices 矩阵: 类似向量的推广, 可以构建更多轴的数据结构 # 构建矩阵 A = torch.arange(20).reshape(5, 4) A.T # 转置 # 对称矩阵 B = torch.tensor([[1, 2, 3], [2, 0, 4], [3, 4, 5]]) B = B.T 形状相同张量的计算 A = torch.arange(20, dtype=torch.float32).reshape(5, 4) B = A.clone() A, A + B A * B # 对应元素相乘: Hadamard 积 计算元素的和 x = torch.arange(4, detype=torch.float64) x.sum() # 任意形状张量的和 计算平均值 A.mean() # 均值 A.sum() / A.numel() # 另一种计算均值的方法: 和 / 数量 点乘是相同位置元素乘积的和 ...

March 21, 2021 · 2 min · 307 words · Starslayerx

Dive into DeepLearning - 01 - Preliminaries

Course Note: d2l-video-04 - 数据操作+数据预处理 Jupyter Notebook: chapter_preliminaries/pandas.ipynb 预备知识中 Data Manipulation 和 Data Preprocessing 的部分 介绍 N 纬数组介绍 0-d (标量) 1.0 一个类别 1-d (向量) [1.0, 2.7, 3.4] 一个特征向量 2-d (矩阵) [[1.0, 2.7, 3.4], [1.0, 2.7, 3.4], [1.0, 2.7, 3.4]] 一个样本 - 特征矩阵 3-d RGB 图片(宽 x 高 x 通道) [[[1.0, 2.7, 3.4], [1.0, 2.7, 3.4], [1.0, 2.7, 3.4]], [[1.0, 2.7, 3.4], [1.0, 2.7, 3.4], [1.0, 2.7, 3.4]]] 4-d 一个 RGB 图片批量 (批量大小 x 宽 x 高 x 通道) ...

March 21, 2021 · 3 min · 566 words · Starslayerx