FastApi - 接收正文请求中的对象列表
FastApi - receive list of objects in body request
我需要创建一个可以接收以下内容的端点 JSON 并识别其中包含的对象:
{
"data": [
{
"start": "A", "end": "B", "distance": 6
},
{
"start": "A", "end": "E", "distance": 4
}
]
}
我创建了一个模型来处理单个对象:
class GraphBase(BaseModel):
start: str
end: str
distance: int
有了它,我可以将它保存在数据库中。但是现在我需要接收对象列表并将它们全部保存。
我试着做这样的事情:
class GraphList(BaseModel):
data: Dict[str, List[GraphBase]]
@app.post("/dummypath")
async def get_body(data: schemas.GraphList):
return data
但我在 FastApi 上不断收到此错误:Error getting request body: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
并在响应中收到此消息:
{
"detail": "There was an error parsing the body"
}
我是 python 的新手,甚至是 FastApi 的新手,如何将 JSON 转换为 GraphBase
的列表以将它们保存在我的数据库中?
这是一个工作示例。
from typing import List
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class GraphBase(BaseModel):
start: str
end: str
distance: int
class GraphList(BaseModel):
data: List[GraphBase]
@app.post("/dummypath")
async def get_body(data: GraphList):
return data
我可以在自动生成的文档上尝试这个 API。
或者,在控制台上(您可能需要根据您的设置调整 URL):
curl -X 'POST' \
'http://localhost:8000/dummypath' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"data": [
{
"start": "string",
"end": "string",
"distance": 0
}
]
}'
错误看起来像是数据问题。我发现你在几个地方有额外的空间。尝试以下操作:
{
"data": [
{
"start": "A", "end": "B", "distance": 6
},
{
"start": "A", "end": "E", "distance": 4
}
]
}
多余空格(我去掉的)位置如下:
我需要创建一个可以接收以下内容的端点 JSON 并识别其中包含的对象:
{
"data": [
{
"start": "A", "end": "B", "distance": 6
},
{
"start": "A", "end": "E", "distance": 4
}
]
}
我创建了一个模型来处理单个对象:
class GraphBase(BaseModel):
start: str
end: str
distance: int
有了它,我可以将它保存在数据库中。但是现在我需要接收对象列表并将它们全部保存。 我试着做这样的事情:
class GraphList(BaseModel):
data: Dict[str, List[GraphBase]]
@app.post("/dummypath")
async def get_body(data: schemas.GraphList):
return data
但我在 FastApi 上不断收到此错误:Error getting request body: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
并在响应中收到此消息:
{
"detail": "There was an error parsing the body"
}
我是 python 的新手,甚至是 FastApi 的新手,如何将 JSON 转换为 GraphBase
的列表以将它们保存在我的数据库中?
这是一个工作示例。
from typing import List
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class GraphBase(BaseModel):
start: str
end: str
distance: int
class GraphList(BaseModel):
data: List[GraphBase]
@app.post("/dummypath")
async def get_body(data: GraphList):
return data
我可以在自动生成的文档上尝试这个 API。
或者,在控制台上(您可能需要根据您的设置调整 URL):
curl -X 'POST' \
'http://localhost:8000/dummypath' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"data": [
{
"start": "string",
"end": "string",
"distance": 0
}
]
}'
错误看起来像是数据问题。我发现你在几个地方有额外的空间。尝试以下操作:
{
"data": [
{
"start": "A", "end": "B", "distance": 6
},
{
"start": "A", "end": "E", "distance": 4
}
]
}
多余空格(我去掉的)位置如下: