FastAPI: 断言错误

huangapple go评论60阅读模式
英文:

FastAPI: AssertionError

问题

当我尝试使用uvicorn启动API时,我遇到以下错误:

"AssertionError: Param: nodes can only be a request body, using Body():"

如何修复这个错误?

英文:

When i try to start the API with uvicorn, i get following error:

"""AssertionError: Param: nodes can only be a request body, using Body():"""

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from typing import List, Dict

app = FastAPI(title="Neo4jAPI")

@app.post("/create_nodes/")
def post(nodes: List[Dict] | None = Header(default=None)):
    #Some Logic
    return JSONResponse(nodes)

How do i fix this error?

答案1

得分: 1

通过定义 nodes: ... = Header(default=None),你告诉 FastAPI 应从请求头中提取 nodes 参数的值。

FastAPI 支持将头部作为单个值提取:例如,使用 user_agent: str = Header() 提取 User-Agent 头的值。
它还支持从头部提取值的列表,如果头部多次指定(参见 https://fastapi.tiangolo.com/lo/tutorial/header-params/)。

但是,它不支持从请求头中提取字典的列表。
你如何在请求头中建模这种情况?

你可能想要的是从请求体中提取节点(可能作为 JSON)。
修复这个问题的简单方法就是删除 = Header(...) 部分。如果只有一个参数,FastAPI 会假定它代表请求体。

@app.post("/create_nodes/")
def post(nodes: List[Dict] | None):
    return JSONResponse(nodes)
英文:

By defining nodes: ... = Header(default=None), you tell FastAPI that the values of the nodes parameter should be extracted from the request headers.

FastAPI supports headers as single values: e.g. extracting the value of the User-Agent header with user_agent: str = Header().
It also supports extracting lists of values from headers, if headers are specified multiple times (see https://fastapi.tiangolo.com/lo/tutorial/header-params/).

However it doesn't support extracting lists of dictionaries from request headers.
How would you even model that in a request header?

What you probably want to do, is extract the nodes from the request body (probably as JSON).
The simple fix for it is just to remove the = Header(...) part. If there is just one parameter, FastAPI assumes that this represents the body.

@app.post("/create_nodes/")
def post(nodes: List[Dict] | None):
    return JSONResponse(nodes)

huangapple
  • 本文由 发表于 2023年5月22日 19:45:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定