FastApi接收body请求中的对象列表

2024-07-01 07:42:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个端点,该端点可以接收以下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列表以保存在数据库中


Tags: 对象数据库json列表databody端点start
1条回答
网友
1楼 · 发布于 2024-07-01 07:42:53

这是一个有效的例子

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

enter image description here

或者,在控制台上(您可能需要根据您的设置调整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
    }
  ]
}

额外空间(我已删除)的位置如下:

enter image description here

相关问题 更多 >

    热门问题