You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中如何将HTTP POST请求映射到模型类及获取请求头

FastAPI 请求处理与 Pydantic 模型映射实现方案

1. 读取 POST 请求并映射到 Pydantic 模型

FastAPI 结合 Pydantic 会自动完成请求体到模型类的映射,不需要手动编写解析代码,只需按以下步骤配置:

  • 从 pydantic 导入 BaseModel,定义匹配请求体结构的模型类
  • 在路由函数中直接将模型作为参数传入,FastAPI 会自动解析、验证请求体并映射到模型实例

修改后的 app.py 示例:

from fastapi import FastAPI, Header
from pydantic import BaseModel

app = FastAPI()

# 定义与客户端请求体结构一致的 Pydantic 模型
class Task(BaseModel):
    userId: int
    title: str
    completed: bool

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

# 注意使用小写的 @app.post,原代码的 @app.POST 是错误写法
@app.post("/test")
async def test(task: Task):
    # 直接通过模型实例访问请求字段
    return {
        "received_userId": task.userId,
        "received_title": task.title,
        "completed_status": task.completed
    }

2. 同时获取请求体与请求头并验证

要获取并验证请求头,使用 FastAPI 提供的 Header 依赖项,直接在路由函数中添加对应参数即可,和 Pydantic 模型参数共存:

示例(验证 Content-Type 头):

@app.post("/test")
async def test(
    task: Task,
    # 用 Header(...) 标记必填请求头,可添加验证规则
    content_type: str = Header(..., description="必须为 application/json; charset=UTF-8")
):
    # 自定义请求头验证逻辑
    if content_type != "application/json; charset=UTF-8":
        return {"error": "请求头 Content-Type 不符合要求"}
    
    return {
        "received_data": task.dict(),
        "validated_header": content_type
    }

核心说明

  • FastAPI 会自动根据 Pydantic 模型校验请求体数据类型,不符合要求时直接返回标准化错误响应
  • 请求头通过 Header 依赖项直接获取,支持设置必填性、默认值及自定义验证逻辑
  • 路由装饰器需使用小写的 @app.post,大写的 @app.POST 会导致路由注册失败

内容的提问来源于stack exchange,提问作者kishi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 06:03:20