FastAPI 核心模块全景解析:从应用路由到后台任务的完整技术地图

原创2026-09-22 15:53:461,630 阅读
文章标签:人工智能AI Agent代码智能体文档教程开发工具

FastAPI 核心模块全景解析:从应用路由到后台任务的完整技术地图

本篇文章以本仓库 AI 生成的 FastAPI 教程索引 及其八个章节为骨架,系统性梳理 FastAPI 的八大核心模块——应用与路由、路径操作与参数声明、Pydantic 数据校验与序列化、OpenAPI 自动文档、依赖注入、错误处理、安全工具与后台任务——并揭示它们之间的调用关系。读完本文,你将掌握 FastAPI 从“零到生产”的完整技术脉络,能独立搭建一个带自动校验、自动文档、安全认证与异步后台任务的高质量 Web API。

FastAPI 是一个基于 Python 的现代高性能 Web 框架,它的设计目标是易用、开发快、可上生产。其三大核心卖点是:基于 Pydantic 的自动数据校验、内置的依赖注入体系,以及基于 OpenAPI 与 Swagger UI 的自动交互式 API 文档。本仓库的 docs/FastAPI/ 目录下,通过 index.md 这张“技术地图”把 FastAPI 的源码抽象为 8 个核心模块,并用一张架构图勾勒出它们之间的依赖关系——这正是本文展开的骨架。

一、整体架构:八大模块及其关系

docs/FastAPI/index.md 用一张 mermaid 流程图定义了 FastAPI 教程系列的模块结构与依赖关系,这是理解整个框架的入口:

flowchart TD
    A0["FastAPI Application & Routing"]
    A1["Path Operations & Parameter Declaration"]
    A2["Data Validation & Serialization (Pydantic)"]
    A3["Dependency Injection"]
    A4["OpenAPI & Automatic Docs"]
    A5["Error Handling"]
    A6["Security Utilities"]
    A7["Background Tasks"]
    A0 -- "Defines Routes for" --> A1
    A1 -- "Uses for parameter/body val..." --> A2
    A1 -- "Uses Depends() for dependen..." --> A3
    A0 -- "Generates API spec for" --> A4
    A0 -- "Manages global" --> A5
    A3 -- "Injects BackgroundTasks object" --> A7
    A6 -- "Uses Depends mechanism (Sec...)" --> A3
    A6 -- "Raises HTTPException on fai..." --> A5
    A4 -- "Reads definitions from" --> A1
    A4 -- "Reads Pydantic models for s..." --> A2
    A4 -- "Reads security scheme defin..." --> A6
    A5 -- "Handles RequestValidationEr..." --> A2

这张图的信息量很大,逐条拆解就是 FastAPI 的“内部关系网”:

关系 含义
A0 → A1 FastAPI 应用对象通过装饰器为路径操作(Path Operations)定义路由
A1 → A2 路径操作依赖 Pydantic 模型完成参数与请求体的类型校验
A1 → A3 路径操作通过 Depends() 声明依赖注入
A0 → A4 应用对象根据所有路径操作自动生成 OpenAPI 规范
A0 → A5 应用对象统一管理全局错误处理
A3 → A7 依赖注入体系负责注入 BackgroundTasks 对象
A6 → A3 安全工具(Security())基于 Depends 机制实现
A6 → A5 安全校验失败时抛出 HTTPException 交由错误处理模块
A4 → A1/A2/A6 OpenAPI 文档分别读取路径操作定义、Pydantic 模型、安全方案定义
A5 → A2 错误处理模块统一接管 Pydantic 抛出的 RequestValidationError

下文逐一展开这八个模块,并在每节给出对应的章节文档链接供深入学习。

二、模块 1:FastAPI 应用与路由(Application & Routing)

对应章节:Chapter 1: FastAPI Application & Routing

FastAPI 应用对象是整个项目的“中央控制塔”,负责把 URL 路径 + HTTP 方法绑定到具体的 Python 函数,这一过程称为路由(Routing)。

2.1 最小可运行应用

# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello World"}

逐行说明:

  • from fastapi import FastAPI:导入核心类;
  • app = FastAPI():创建应用实例(按惯例命名为 app);
  • @app.get("/"):装饰器,告诉 FastAPI「收到对 / 的 GET 请求时执行下方函数」;
  • async def read_root():异步函数,FastAPI 基于 asyncio 构建,路由函数通常用 async def 声明;
  • return {"message": "Hello World"}:返回 Python 字典,FastAPI 会自动将其序列化为 JSON。

2.2 用 Uvicorn 运行

FastAPI 应用由 ASGI 服务器(如 Uvicorn)承载:

pip install fastapi uvicorn[standard]
uvicorn main:app --reload

命令拆解:main 指 main.py 文件,app 指文件内名为 app 的实例;--reload 让服务器在保存代码后自动重启(开发期利器)。启动后访问 http://127.0.0.1:8000,浏览器会看到:

{"message":"Hello World"}

2.3 用 APIRouter 组织路由

真实项目路由众多,全部堆在 main.py 会难以维护。APIRouter 相当于“迷你应用/章节”,把相关路由分组到独立文件,再挂载回主应用:

# routers/items.py
from fastapi import APIRouter

router = APIRouter()

@router.get("/items/")
async def read_items():
    return [{"name": "Item Foo"}, {"name": "Item Bar"}]

@router.get("/items/{item_id}")
async def read_item(item_id: str):
    return {"item_id": item_id, "name": f"Item {item_id}"}
# main.py
from fastapi import FastAPI
from routers import items

app = FastAPI()
app.include_router(items.router)

@app.get("/")
async def read_root():
    return {"message": "Hello Main App!"}

挂载后 /items/、/items/{item_id} 均生效,app.include_router() 是核心连接点。

2.4 底层原理

一个请求的生命周期为:浏览器发 GET / → Uvicorn 按 ASGI 标准把请求交给 FastAPI → 应用在路由表中匹配方法与路径 → 调用对应函数 → 返回值序列化为 JSON(自动附带 Content-Type: application/json)→ 经 Uvicorn 返回浏览器。从源码结构看,FastAPI 在 Starlette 的路由能力之上构建:@app.get() / @router.get() 会把路径、方法与处理函数注册为 Route 对象列表(概念上位于 fastapi/routing.py 与 starlette/routing.py),include_router() 则把这些路由(可带路径前缀)并入主应用的路由列表,请求到达时按序做路径模式匹配与方法检查。

三、模块 2:路径操作与参数声明(Path Operations & Parameter Declaration)

对应章节:Chapter 2: Path Operations & Parameter Declaration

路径操作解决的核心问题是:如何把 URL 路径、查询串、请求体中的信息提取出来、做类型校验,并注入到函数参数中。FastAPI 的做法是用标准 Python 类型提示“变魔术”。

3.1 不止 GET:五种 HTTP 方法

方法 语义
GET 读取数据
POST 创建数据
PUT 整体更新数据
PATCH 局部更新数据
DELETE 删除数据

FastAPI 为每个方法提供对应装饰器:@app.post()、@app.put()、@app.patch()、@app.delete(),用法与 @app.get() 一致;同一路径下不同方法可绑定不同函数。

3.2 路径参数(Path Parameters)

用花括号 {} 在路径中声明变量,函数参数名必须一致:

@app.get("/items/{item_id}")
async def read_item(item_id: int):  # 类型提示 : int 是关键
    return {"item_id": item_id, "name": f"Item {item_id} Name"}

int 类型提示让 FastAPI 自动完成两件事:把 URL 中的字符串 "5" 转成整数 5;访问 /items/abc 时自动返回 422 校验错误(int_parsing 类型、loc 指明出错位置为 path.item_id),函数根本不会执行。路径参数是路径中必填的部分,缺失即无法匹配路由。

3.3 查询参数(Query Parameters)

不在路径中出现的函数参数即为查询参数,带默认值即为可选:

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]

访问 /items/?skip=1&limit=1 返回 [{"item_name":"Bar"}];?limit=abc 则自动报校验错误。不带默认值的查询参数则变为必填;也可使用 bool、float、str | None = None(Python 3.10+ 写法,旧版本用 Optional[str])等类型。

3.4 请求体(Request Body):Pydantic 模型初探

对于 POST/PUT/PATCH,复杂数据通常以 JSON 放在请求体中,用 Pydantic 模型定义其结构:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str | None = None  # 可选字段
    price: float
    tax: float | None = None        # 可选字段

@app.post("/items/")
async def create_item(item: Item):
    item_dict = item.model_dump()   # Pydantic v2:模型转 dict
    if item.tax:
        item_dict["price_with_tax"] = item.price + item.tax
    return item_dict

FastAPI 识别到参数类型是 Pydantic 模型后,自动读取请求体 → 解析 JSON → 按模型校验(必填字段、类型)→ 通过后以 Item 实例传入函数,失败则返回 422 错误。一个函数只能声明一个请求体参数(但该模型内部可嵌套复杂结构)。

3.5 用 Path/Query/Body 精细化控制

结合 typing.Annotated 可附加更强校验规则与元数据:

from typing import Annotated
from fastapi import FastAPI, Path, Query

@app.get("/items/{item_id}")
async def read_item(
    item_id: Annotated[int, Path(
        title="The ID of the item to get",
        gt=0,     # Greater Than
        le=1000   # Less Than or Equal
    )]
):
    return {"item_id": item_id, "name": f"Item {item_id} Name"}

@app.get("/items/")
async def read_items(
    q: Annotated[str | None, Query(min_length=3, max_length=50)] = None,
    skip: Annotated[int, Query(ge=0)] = 0,          # ge = Greater Than or Equal
    limit: Annotated[int, Query(gt=0, le=100)] = 10
):
    results = fake_items_db[skip : skip + limit]
    if q:
        results = [item for item in results if q.lower() in item["item_name"].lower()]
    return results

要点:

  • Annotated[类型, 工具] 是 Python 3.9+ 标准写法,FastAPI 用它把 Path/Query/Body 与参数绑定;
  • Path() 用于路径参数,Query() 用于查询参数,Body() 用于请求体;
  • 数值校验:gt(大于)、ge(大于等于)、lt(小于)、le(小于等于);
  • 字符串校验:min_length、max_length;
  • Header()、Cookie()、File() 分别对应请求头、Cookie、上传文件,用法相同;
  • 元数据(title、description)会出现在自动文档中(见模块 4)。

3.6 底层原理

FastAPI 在应用启动时用 Python 的 inspect 机制分析每个路径操作函数的签名:参数名命中路径变量({item_id})→ 路径参数;类型是 Pydantic 模型 → 请求体参数;其余 → 查询参数;Annotated 中的 Path/Query 等则显式指定来源。请求到达后,FastAPI 完成提取 → 转换 → 校验,任一环节失败立即返回 422,函数不被调用;全部通过后才以 read_item(item_id=5) 这样的形式调用处理函数。

四、模块 3:数据校验与序列化(Pydantic)

对应章节:Chapter 3: Data Validation & Serialization (Pydantic)

Pydantic 在 FastAPI 中扮演双重角色:校验(门卫)——按蓝图检查入站数据;序列化(翻译官)——把出站 Python 对象转成 JSON。

4.1 定义模型

Pydantic 模型即继承 pydantic.BaseModel 的类,字段用类属性 + 类型提示声明:

from pydantic import BaseModel

class Item(BaseModel):
    name: str                          # 必填,必须是字符串
    description: str | None = None     # 可选(str 或 None),默认 None
    price: float                       # 必填,浮点数
    tax: float | None = None           # 可选
  • str | None(联合类型)表示字段可以是字符串或 None;
  • = None 提供默认值,使字段可选;入站数据缺失该字段时自动置为 None;
  • 无默认值的字段为必填。

4.2 入站校验:请求体即“蓝图”

@app.post("/items/")
async def create_item(item: Item):
    print(f"Received item name: {item.name}")
    return item.model_dump()

客户端发送 {"name": "Thingamajig", "price": 49.99} 时自动通过校验,description、tax 取默认值 None;若发送 {"name": "Gadget"}(缺 price)或 {"name": "Gizmo", "price": "expensive"}(类型错误),FastAPI 不会调用 create_item,而是返回 422,错误体包含 type(如 missing、float_parsing)、loc(如 ["body", "price"])、msg、input 等结构化信息——这些校验逻辑零样板代码。

4.3 出站序列化:response_model 过滤与定型

用 response_model 可精确控制对外返回的字段,隐藏内部敏感数据:

from pydantic import BaseModel

# 输入模型(可含内部字段)
class ItemCreate(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None
    internal_cost: float          # 内部成本,不想暴露

# 输出模型(客户端可见字段)
class ItemPublic(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None
    # 故意不定义 internal_cost

@app.post("/items/", response_model=ItemPublic)
async def create_item(item_input: ItemCreate):
    item_data = item_input.model_dump()
    # ... 存入数据库,返回含 internal_cost 的 dict ...
    return saved_item_data

客户端发送含 internal_cost 的 JSON 后,响应体中 internal_cost 与模拟生成的 id 均被自动剔除,只返回 ItemPublic 定义的字段。response_model 的价值在于:过滤字段 + 输出校验 + 自动序列化,让 API 的输出契约清晰可控。

4.4 底层原理

一条 POST /items/ 请求的完整链路:

  1. 路由匹配到 create_item;
  2. FastAPI 发现 item_input 类型为 Pydantic 模型,定位到请求体;
  3. 读取并解析 JSON,本质调用 ItemCreate.model_validate(parsed_dict);
  4. 校验失败 → Pydantic 抛 ValidationError → FastAPI 转成 422 JSON 响应(create_item 永不执行);
  5. 校验成功 → 调用函数;
  6. 返回值经 response_model 过滤,再由 fastapi.encoders.jsonable_encoder 递归转换(Pydantic 模型走 .model_dump(mode='json'),datetime/UUID/Decimal 等转成 JSON 兼容类型)后发出。

从源码结构看,参数分析在 fastapi.dependencies.utils.analyze_param,请求体读取与校验在 request_body_to_args,422 由 fastapi.exception_handlers 中的默认处理器生成,response_model 处理在 fastapi.routing.APIRoute,JSON 转换则由 fastapi.encoders.jsonable_encoder 完成。

五、模块 4:OpenAPI 与自动文档

对应章节:Chapter 4: OpenAPI & Automatic Docs

FastAPI 最大的“免费午餐”之一:直接从代码生成行业标准的 OpenAPI 规范,并自带两套交互式文档界面,文档永远与代码同步。

5.1 自动生成:从代码到文档

FastAPI 通过检查路径操作装饰器(路径与方法)、函数参数与类型提示、Path()/Query() 元数据、Pydantic 模型(请求体与 response_model)、docstring 与 tags/summary 等,自动生成 OpenAPI 文档。因此改代码即改文档——参数类型变了、新增了端点,下次启动应用文档就更新。

5.2 三处开箱即用的文档入口

uvicorn main:app --reload
URL 说明
http://127.0.0.1:8000/docs Swagger UI:按标签分组浏览端点,可查看参数、请求体结构、响应定义,还带“Try it out”按钮直接在浏览器里真实调用 API 做测试
http://127.0.0.1:8000/redoc ReDoc:三栏式纯阅读视图,适合通读 API 结构
http://127.0.0.1:8000/openapi.json 机器可读的原始 OpenAPI JSON,可用于自动生成客户端代码、跑测试

5.3 让文档更丰富

app = FastAPI(
    title="My Super API",
    description="This is a very fancy API built with FastAPI",
    version="1.0.0",
)

@app.post("/items/", response_model=Item, tags=["Items"])
async def create_item(item: Item):
    """Create a new item and store it."""
    ...

再配合 Pydantic 的 Field 为模型字段补充描述与示例:

from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str = Field(..., title="Item Name", example="Super Gadget")
    description: str | None = Field(default=None, max_length=300, example="A very useful gadget.")
    price: float = Field(..., gt=0, title="Price", example=19.99)
    tax: float | None = Field(default=None, ge=0, example=1.60)

这些元数据会呈现在 /docs 底部的 Schemas 区,大大提升文档可读性。

5.4 底层原理

从源码结构看:应用启动时,fastapi.openapi.utils.get_openapi 遍历全部路径操作,用 fastapi.openapi.models 中的 OpenAPI、Info、PathItem、Operation、Schema 等 Pydantic 模型组装文档结构,Pydantic 模型则转为 JSON Schema 放进 components.schemas。FastAPI 自动注册三个路由:/openapi.json(调用 get_openapi 返回 JSON)、/docs(用 fastapi.openapi.docs.get_swagger_ui_html 生成加载 Swagger UI 的 HTML)、/redoc(同理加载 ReDoc)。浏览器访问 /docs 时,页面 JS 会再向 /openapi.json 发起请求拿到 schema 后动态渲染——文档与代码天然一致,是一等公民而非事后补充。

六、模块 5:依赖注入(Dependency Injection)

对应章节:Chapter 5: Dependency Injection

依赖注入解决“多个端点共享同一套准备逻辑”的重复代码问题(如数据库会话、登录校验、分页参数),遵循 DRY 原则,让代码更模块化、可复用。

6.1 核心概念

  • 依赖(Dependency):为路径操作(或其它依赖)提供值的可调用对象,如“取当前用户”“连数据库”“解析公共查询参数”的函数;
  • Depends:从 fastapi 导入的特殊函数,写法 参数: Annotated[返回类型, Depends(依赖函数)],用于声明“我需要这个依赖”;
  • 注入(Injection):FastAPI 自动调用依赖函数,把其返回值注入到路径操作的参数中;
  • 每请求缓存(Caching):默认情况下,同一请求中同一依赖只执行一次,结果复用(如数据库连接),可通过 Depends(..., use_cache=False) 关闭;
  • 层级(Hierarchy):依赖可以再依赖其它依赖,形成依赖树,FastAPI 自动解析整条链。

6.2 基础示例:共享分页参数

# common_dependencies.py
from typing import Annotated
from fastapi import Query

async def common_parameters(
    q: Annotated[str | None, Query(description="Optional query string")] = None,
    skip: Annotated[int, Query(description="Items to skip", ge=0)] = 0,
    limit: Annotated[int, Query(description="Max items to return", le=100)] = 100,
):
    return {"q": q, "skip": skip, "limit": limit}
# routers/items.py
from typing import Annotated
from fastapi import APIRouter, Depends
from ..common_dependencies import common_parameters

router = APIRouter()

@router.get("/items/")
async def read_items(
    commons: Annotated[dict, Depends(common_parameters)]  # 依赖注入!
):
    q = commons["q"]
    skip = commons["skip"]
    limit = commons["limit"]
    ...

@router.get("/users/")
async def read_users(
    commons: Annotated[dict, Depends(common_parameters)]  # 复用同一依赖
):
    ...

Depends(common_parameters) 告诉 FastAPI:调用 read_items 前,先从请求里取 q/skip/limit 传给 common_parameters,把返回值注入到 commons 参数。多个端点复用同一依赖,分页逻辑只写一次。

6.3 依赖的依赖(链式解析)

async def get_db_session():
    print("Getting DB Session")
    return "fake_db_session_123"

async def get_item_from_db(
    item_id: int,  # 普通路径参数
    db: Annotated[str, Depends(get_db_session)]  # 依赖 get_db_session
):
    fake_db = {1: "Item One", 2: "Item Two"}
    if item_id not in fake_db:
        raise HTTPException(status_code=404, detail="Item not found in DB")
    return fake_db[item_id]

@router.get("/db_items/{item_id}")
async def read_db_item(
    item_id: int,  # 路径参数(get_item_from_db 也需要它)
    item_name: Annotated[str, Depends(get_item_from_db)]
):
    return {"item_id": item_id, "name_from_db": item_name}

请求 GET /db_items/2 时,FastAPI 自动按 read_db_item → get_item_from_db → get_db_session 的顺序解析:路径参数 item_id 会在链中共享,get_db_session 的结果被传给下层依赖,最终 item_name 拿到 "Item Two"。若 get_db_session 同时被多个依赖需要,由于默认缓存,整个请求中它仍只执行一次。

6.4 底层原理

从源码结构看:

  • fastapi.Depends(位于 fastapi/param_functions.py)本质是一个标记类;
  • fastapi.dependencies.utils.get_dependant 检查可调用对象签名,识别路径/查询/请求体参数与 Depends 标记的依赖,构建 Dependant 对象;
  • fastapi.dependencies.models.Dependant 保存可调用对象、其参数及子依赖列表,构成依赖树;
  • fastapi.dependencies.utils.solve_dependencies 是解析引擎:递归遍历依赖图、查询缓存(dependency_cache)、通过 run_in_threadpool 执行同步函数或 await 异步函数、处理 yield 生成器,最后收集全部值调用目标路径操作函数。

七、模块 6:错误处理(Error Handling)

对应章节:Chapter 6: Error Handling

错误处理让 API 在“预期内失败”与“意外输入”时都能优雅地告知客户端,而不是崩溃或返回含糊的 500。

7.1 预期错误:HTTPException

from fastapi import FastAPI, HTTPException

fake_items_db = {1: {"name": "Foo"}, 2: {"name": "Bar"}}

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id not in fake_items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": fake_items_db[item_id]}
  • status_code=404 指定标准 HTTP 状态码(也可用 from starlette import status 的常量如 status.HTTP_404_NOT_FOUND 提升可读性);
  • detail="Item not found" 是人类可读的错误消息,会以 JSON 形式返回给客户端;
  • 访问 /items/99 时客户端收到 {"detail": "Item not found"},状态码 404。

7.2 自动校验错误:RequestValidationError

当入站数据不满足类型提示或 Pydantic 模型规则时,FastAPI 自动拦截并返回 422,无需任何 try/except:

{
  "detail": [
    {
      "type": "missing",
      "loc": ["body", "price"],
      "msg": "Field required",
      "input": {"name": "Widget"}
    }
  ]
}

loc 精确指出错误位置,type 说明错误类型(missing、float_parsing、int_parsing 等),客户端能立即知道哪里写错了。

7.3 自定义异常处理器

用 @app.exception_handler() 注册自定义处理逻辑,实现完全自定义的错误响应格式:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

class UnicornNotFound(Exception):
    def __init__(self, name: str):
        self.name = name

app = FastAPI()

@app.exception_handler(UnicornNotFound)
async def unicorn_exception_handler(request: Request, exc: UnicornNotFound):
    return JSONResponse(
        status_code=418,  # I'm a teapot!
        content={"message": f"Oops! Can't find unicorn named: {exc.name}."},
    )

@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornNotFound(name=name)
    return {"unicorn_name": name, "message": "Unicorn exists!"}

7.4 底层原理

  • 抛出 HTTPException 后,FastAPI 用默认处理器 fastapi.exception_handlers.http_exception_handler 生成 {"detail": exc.detail} 的 JSONResponse;
  • Pydantic 校验失败时抛 pydantic.ValidationError,FastAPI 用 fastapi.exceptions.RequestValidationError 包装,再由 request_validation_exception_handler 调用 jsonable_encoder(exc.errors()) 生成 422 响应,路径操作函数从未被调用;
  • HTTPException 与 RequestValidationError 定义于 fastapi/exceptions.py,默认处理器在 fastapi/exception_handlers.py,exception_handler 方法属于 fastapi/applications.py 中的 FastAPI 类。

八、模块 7:安全工具(Security Utilities)

对应章节:Chapter 7: Security Utilities

安全工具解决**认证(Authentication,证明你是谁)与授权(Authorization,检查你能做什么)**两大问题,fastapi.security 模块提供了开箱即用的安全方案类。

8.1 核心模式:方案实例 → 校验依赖 → Security(校验器)

概念 类比
安全方案类(HTTPBasic、APIKeyHeader、OAuth2PasswordBearer) 锁的类型
方案实例(security = HTTPBasic()) 装好的锁
凭据(用户名/密码、API Key、token) 钥匙
校验依赖(get_current_username) 查钥匙对不对的门卫
Security(校验依赖) 门上挂“需开锁”标识(并在 /docs 显示锁图标)

8.2 HTTP Basic 认证完整示例

from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials

security = HTTPBasic()
app = FastAPI()

def get_current_username(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
    # 真实项目中绝不应硬编码凭据!应使用 passlib 等安全哈希并查数据库
    correct_username = "stanley"
    correct_password = "password123"  # 仅演示用
    if not (credentials.username == correct_username and credentials.password == correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},  # 401 Basic Auth 必需头
        )
    return credentials.username

@app.get("/users/me")
async def read_current_user(
    username: Annotated[str, Security(get_current_username)]
):
    return {"username": username}

行为验证:

  • /docs 中 /users/me 旁出现锁图标,点“Authorize”输入 stanley/password123 后即可在页面内真实调用;
  • curl http://127.0.0.1:8000/users/me → {"detail":"Not authenticated"}(401);
  • curl -u wronguser:wrongpass http://127.0.0.1:8000/users/me → {"detail":"Incorrect email or password"}(401);
  • curl -u stanley:password123 http://127.0.0.1:8000/users/me → {"username": "stanley"}(200)。

Security() 与 Depends() 几乎相同,但额外会把安全需求写入 OpenAPI 文档,从而在 /docs 显示锁图标与凭据输入 UI。

8.3 其它常用方案

API Key 放在请求头:

from fastapi.security import APIKeyHeader

api_key_header_scheme = APIKeyHeader(name="X-API-KEY", auto_error=False)

async def verify_api_key(api_key: Annotated[str | None, Security(api_key_header_scheme)]):
    if api_key is None:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="X-API-KEY header missing")
    if api_key == "SECRET_API_KEY":
        return api_key
    raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API Key")

@app.get("/secure-data")
async def get_secure_data(
    verified_key: Annotated[str, Security(verify_api_key)]
):
    return {"data": "sensitive data", "key": verified_key}

OAuth2 密码 Bearer 流程(Web 应用登录常见):

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.post("/token")
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()]
):
    # 1. 校验用户名/密码  2. 生成访问令牌(如 JWT) 3. 返回
    access_token = f"token_for_{form_data.username}"  # 演示用
    return {"access_token": access_token, "token_type": "bearer"}

async def get_current_user(token: Annotated[str, Security(oauth2_scheme)]):
    # 真实应用中:解码 JWT → 校验过期与签名 → 提取用户 → 查库
    if token == "token_for_stanley":
        return {"username": "stanley", "email": "stanley@example.com"}
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid authentication credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )

@app.get("/users/me/oauth")
async def read_users_me_oauth(
    current_user: Annotated[dict, Security(get_current_user)]
):
    return current_user

另有 APIKeyQuery、APIKeyCookie(Key 放查询串/Cookie)、HTTPBearer、HTTPDigest、OAuth2AuthorizationCodeBearer 等,模式完全一致。

8.4 底层原理

以 Basic Auth 为例,HTTPBasic.__call__(request) 读取 Authorization 头、base64 解码出 用户名:密码,封装为 HTTPBasicCredentials 返回;校验依赖拿到凭据后决定放行或抛 401;Security() 则让 OpenAPI 生成器把对应方案写入 components.securitySchemes 并在端点级引用,这就是 /docs 锁图标的来源。从源码结构看:fastapi.Security 是 fastapi.params.Security 的薄包装(继承自 Depends,额外支持 scopes),方案实现分布在 fastapi.security.http(HTTPBasic/HTTPBearer 等)、fastapi.security.api_key(APIKeyHeader/Query/Cookie)、fastapi.security.oauth2(OAuth2 系列)中。

九、模块 8:后台任务(Background Tasks)

对应章节:Chapter 8: Background Tasks

后台任务让 API 在响应已发送给客户端之后再执行慢速、非关键的操作(发欢迎邮件、通知管理员、写日志),保证主操作响应迅速。

9.1 使用三步曲

Step 1:导入 BackgroundTasks:

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

Step 2:定义任务函数(普通 def 或 async def 均可):

def write_log(message: str):
    with open("log.txt", mode="a") as log_file:
        log_file.write(message + "\n")
    print(f"Log written: {message}")

Step 3:注入对象并调用 add_task:

@app.post("/send-notification/{email}")
async def send_notification(
    email: str,
    background_tasks: BackgroundTasks  # 依赖注入获得 BackgroundTasks 对象
):
    log_message = f"Notification sent to: {email}"
    background_tasks.add_task(write_log, log_message)  # 只登记,不立即执行
    return {"message": "Notification sent successfully!"}

验证:curl -X POST http://127.0.0.1:8000/send-notification/test@example.com 会立即收到 {"message":"Notification sent successfully!"},随后 Uvicorn 控制台才打印 Log written: Notification sent to: test@example.com,项目目录下生成含该内容的 log.txt——任务确实在响应之后才执行。

9.2 底层原理

从源码结构看:fastapi.BackgroundTasks(位于 fastapi/background.py)直接继承自 starlette.background.BackgroundTasks,add_task 只是调用父类方法,把 (可调用对象, args, kwargs) 存入内部列表。响应发送由 Starlette 中间件完成:路径函数返回后,中间件先把 200 响应发给客户端,再遍历 BackgroundTasks 中的任务执行(通过 anyio.create_task_group().start_soon() 等机制)。因此后台任务天然位于请求-响应主流程之外,不会拖慢用户。

十、从零搭建完整示例:八大模块串联

把前面八节串成一个可运行的完整示例(含路由、参数、Pydantic 校验、自动文档、依赖注入、错误处理与后台任务):

# main.py
from typing import Annotated
from fastapi import FastAPI, Depends, HTTPException, Path, Query, BackgroundTasks
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str = Field(..., title="Item Name", example="Super Gadget")
    description: str | None = Field(default=None, max_length=300)
    price: float = Field(..., gt=0, example=19.99)
    tax: float | None = Field(default=None, ge=0)

app = FastAPI(title="My Super API", version="1.0.0")
items_db: dict[int, Item] = {}

def write_log(message: str):
    print(f"[background] {message}")

async def common_parameters(
    skip: Annotated[int, Query(ge=0)] = 0,
    limit: Annotated[int, Query(gt=0, le=100)] = 10,
):
    return {"skip": skip, "limit": limit}

@app.post("/items/", response_model=Item, tags=["Items"])
async def create_item(item: Item, background_tasks: BackgroundTasks):
    item_id = len(items_db) + 1
    items_db[item_id] = item
    background_tasks.add_task(write_log, f"item {item_id} created")
    return item

@app.get("/items/{item_id}", response_model=Item, tags=["Items"])
async def read_item(item_id: Annotated[int, Path(gt=0)]):
    if item_id not in items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    return items_db[item_id]

@app.get("/items/", tags=["Items"])
async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
    return list(items_db.values())[commons["skip"] : commons["skip"] + commons["limit"]]

运行 uvicorn main:app --reload 后:

  • GET /items/ 与 GET /items/{item_id} 展示查询/路径参数自动校验;
  • POST /items/ 展示请求体 Pydantic 校验、response_model 输出定型与后台任务;
  • GET /docs 展示自动生成的交互式文档(标题、标签分组、Schemas);
  • GET /items/999 返回 404 JSON 错误。

结语:如何继续深入

本仓库的 FastAPI 教程索引 为这个框架绘制了清晰的学习地图,八章内容可逐篇研读:

  1. FastAPI 应用与路由
  2. 路径操作与参数声明
  3. Pydantic 数据校验与序列化
  4. OpenAPI 与自动文档
  5. 依赖注入
  6. 错误处理
  7. 安全工具
  8. 后台任务

掌握这八个模块及其依赖关系(应用路由 → 参数与校验 → 依赖注入 → 文档/错误/安全/后台任务),你就拥有了从零构建健壮、可维护、自带文档与安全的 FastAPI 服务的完整能力。更进阶的方向包括 WebSocket、中间件、大型应用拆分、测试与部署,可以在此基础上继续探索。

登录后查看全文
Tutorial-Codebase-Knowledge