一、路径参数(含字符串校验)

1. 基础路径参数

路径参数是 URL 中固定位置的参数,用于标识特定资源,FastAPI 支持直接通过函数参数声明。

from fastapi import FastAPI

app = FastAPI()

# 基础路径参数:匹配 /items/1、/items/2 等
@app.get("/items/{item_id}")
async def read_item(item_id: int):  # 指定类型,FastAPI 自动校验+转换
    return {"item_id": item_id}

2. 字符串校验(使用 Path 类)

通过 fastapi.Path 可对路径参数做更精细的校验(长度、正则、取值范围等),同时支持添加描述。

from fastapi import FastAPI, Path

app = FastAPI()

# 带字符串/数值校验的路径参数
@app.get("/items/{item_id}")
async def read_item(
    # gt: 大于,lt: 小于,title/description 用于自动生成文档
    item_id: int = Path(..., gt=0, lt=1000, title="物品ID", description="必须是1-999之间的整数"),
    # 字符串长度校验 + 正则匹配(以字母开头)
    name: str = Path(..., min_length=3, max_length=50, pattern="^[a-zA-Z].*$")
):
    return {"item_id": item_id, "name": name}

关键说明

  • ... 表示参数必填(不可省略);
  • 数值校验:gt(大于)、ge(大于等于)、lt(小于)、le(小于等于);
  • 字符串校验:min_length/max_length(长度)、pattern(正则表达式);
  • 校验失败时,FastAPI 自动返回 422 错误(包含详细校验信息)。

二、查询参数(含字符串校验)

1. 基础查询参数

查询参数是 URL 中 ? 后的键值对(如 /items/?skip=0&limit=10),FastAPI 自动识别未声明为路径参数的函数参数为查询参数。

from fastapi import FastAPI

app = FastAPI()

# 基础查询参数:skip 和 limit 是查询参数,默认值分别为0和10
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

2. 字符串校验(使用 Query 类)

通过 fastapi.Query 对查询参数做校验,用法与 Path 类似。

from fastapi import FastAPI, Query

app = FastAPI()

# 带校验的查询参数
@app.get("/items/")
async def read_items(
    # 可选参数(默认None),长度3-50,正则匹配邮箱格式
    q: str | None = Query(None, min_length=3, max_length=50, pattern=r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"),
    # 必填参数,取值范围1-100
    page: int = Query(..., ge=1, le=100)
):
    return {"q": q, "page": page}

三、请求体(含请求头字段、嵌套模型)

1. 基础请求体(Pydantic 模型)

请求体通过 Pydantic 模型定义,FastAPI 自动解析 JSON 请求体并校验字段。

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# 基础请求体模型
class Item(BaseModel):
    name: str
    price: float
    is_offer: bool | None = None  # 可选字段

@app.post("/items/")
async def create_item(item: Item):  # 接收请求体
    return {"item_name": item.name, "item_price": item.price}

2. 请求头字段

通过 fastapi.Header 声明请求头参数,自动处理头信息的大小写和连字符(如 user-agentuser_agent)。

from fastapi import FastAPI, Header

app = FastAPI()

@app.post("/items/")
async def create_item(
    item: Item,
    # 获取请求头:User-Agent、X-Token(支持多个值)
    user_agent: str | None = Header(None),
    x_token: list[str] | None = Header(None)
):
    return {
        "item": item,
        "user_agent": user_agent,
        "x_token": x_token
    }

3. 嵌套模型

Pydantic 模型支持嵌套,可定义复杂的请求体结构。

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr

app = FastAPI()

# 嵌套子模型
class User(BaseModel):
    username: str
    email: EmailStr  # 内置邮箱格式校验
    full_name: str | None = None

# 主模型(嵌套 User 模型)
class Item(BaseModel):
    name: str
    price: float
    tax: float | None = None
    owner: User  # 嵌套用户模型
    tags: list[str] = []  # 列表字段

@app.post("/items/")
async def create_item(item: Item):
    return item

四、Cookie 参数

通过 fastapi.Cookie 声明 Cookie 参数,FastAPI 自动从请求的 Cookie 中提取值。

from fastapi import FastAPI, Cookie

app = FastAPI()

@app.get("/items/")
async def read_items(
    # 获取 Cookie:session_id(可选)、theme(可选)
    session_id: str | None = Cookie(None),
    theme: str | None = Cookie(None)
):
    return {"session_id": session_id, "theme": theme}

五、Header 参数(补充)

Header 参数除了上述结合请求体的用法,也可单独使用,核心特点:

  1. 自动处理头信息的命名转换(如 X-Forwarded-Forx_forwarded_for);
  2. 支持指定默认值、校验规则(与 Query/Path 一致)。
from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/headers/")
async def read_headers(
    # 校验 Header 参数:必须是 json 或 xml
    accept_format: str = Header(..., pattern="^(json|xml)$")
):
    return {"accept_format": accept_format}

六、响应模型

通过 response_model 参数指定接口返回的模型,FastAPI 自动校验返回值、生成文档,并支持字段过滤。

1. 基础响应模型

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# 定义响应模型
class ItemResponse(BaseModel):
    name: str
    price: float
    is_offer: bool | None = None

    # 配置:允许返回模型中未定义的字段(如数据库额外字段)
    class Config:
        extra = "allow"

@app.post("/items/", response_model=ItemResponse)
async def create_item(item: Item):
    # 即使返回额外字段(如 id),响应仍会按 ItemResponse 过滤
    return {"name": item.name, "price": item.price, "is_offer": item.is_offer, "id": 1}

2. 响应状态码

可通过 status_code 指定响应状态码,结合响应模型使用:

@app.post("/items/", response_model=ItemResponse, status_code=201)  # 201 Created
async def create_item(item: Item):
    return item

七、文件上传

FastAPI 支持单文件 / 多文件上传,通过 fastapi.UploadFile 处理(支持异步、文件元信息获取)。

1. 单文件上传

from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    # UploadFile 属性:filename(文件名)、content_type(文件类型)、file(文件对象)
    return {
        "filename": file.filename,
        "content_type": file.content_type,
        "file_size": len(await file.read())  # 读取文件内容(异步)
    }

2. 多文件上传

@app.post("/uploadfiles/")
async def create_upload_files(files: list[UploadFile] = File(...)):
    return {
        "filenames": [file.filename for file in files],
        "total_files": len(files)
    }

关键说明:

  • UploadFilebytes 更友好(支持大文件、异步读取、获取文件名 / 类型);
  • 可通过 File(..., description="上传的文件") 添加文档描述;
  • 支持文件类型校验(结合 Query/Path 风格的校验)。

总结

  1. 参数声明:路径参数用 Path、查询参数用 Query、Cookie/Header 分别用 Cookie/Header,均支持校验规则(长度、正则、数值范围);
  2. 请求体:基于 Pydantic 模型定义,支持嵌套、字段校验,请求头可通过 Header 单独提取;
  3. 核心扩展:响应模型通过 response_model 规范返回格式,文件上传用 UploadFile 处理(单 / 多文件),所有功能均自动生成 OpenAPI 文档(访问 /docs 查看)。

快速测试

启动代码后,访问 http://127.0.0.1:8000/docs 可打开自动生成的 Swagger UI,直接测试所有接口,验证参数校验、请求体解析、文件上传等功能。

 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐