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

FastAPI路由报错:TypeError: root()缺少必需参数'request'

解决FastAPI中TypeError: root() missing 1 required positional argument: 'request'错误

错误根源是你误用了Flask风格的@app.route装饰器,FastAPI不支持这种写法。它依赖自身的HTTP方法装饰器(如@app.get、@app.post等)来处理Request对象的自动注入逻辑,用错装饰器会导致Request参数无法被正确传递,从而触发报错。

修正后的代码如下:

from fastapi import FastAPI, Request

app = FastAPI()

# 使用FastAPI的GET方法装饰器,若需支持其他HTTP方法,可替换为对应装饰器
@app.get("/{full_path:path}")
async def root(full_path: str, request: Request):
    print(request.method, full_path)
    return "HIYO"

如果需要匹配所有HTTP方法,可以用api_route装饰器:

@app.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
async def root(full_path: str, request: Request):
    print(request.method, full_path)
    return "HIYO"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:08:11