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

FastAPI+Python POST请求报Invalid header 400错误,求排查原因

问题分析与解决方法

你遇到的400错误(Invalid header)是代码里的两个关键缩进错误导致的:

  • 路由装饰器位置错误:你把@router.post("/create_user/")放在了UserCreate这个Pydantic模型类的内部。FastAPI的路由装饰器必须用来装饰独立的视图函数,不能嵌套在模型类里,否则路由无法被正确注册,请求解析时会出错。
  • 路由器挂载代码缩进错误:app.include_router(router, prefix="/mytest")这行代码同样被缩进在了UserCreate类内部,这会导致路由器根本没被挂载到FastAPI应用实例上,自然无法处理请求。

修正后的代码

from fastapi import APIRouter, HTTPException, Request, FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel

app = FastAPI()
router = APIRouter()


class UserCreate(BaseModel):
    user_id: int
    username: str


@router.post("/create_user/")
def create_user(user_data: UserCreate):
    return {
        "msg": "Data received successfully",
        "user_id": user_data.user_id,
        "username": user_data.username,
    }

app.include_router(router, prefix="/mytest")

修正后,路由函数和路由器挂载代码都处于顶层作用域,不再嵌套在模型类里,此时用daphne或uvicorn启动应用,请求POST /mytest/create_user/就能正常处理了。

而你第二个能正常运行的代码,是因为路由装饰器直接正确装饰了视图函数,且没有缩进错误,所以可以正常处理请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:05:07