FastApi - 从 php 数组接收有效负载

问题描述 投票:0回答:1

我在 FastAPI 应用程序上收到以下错误。该错误与来自 PHP 数组的有效负载有关。我可以将 input_data 更改为另一种类型,我的挑战是输入看起来确实像常规字典,所以我不知道如何允许将此数组读取为字典。

async def post(input_data:dict):

{#908
  +"detail": array:1 [
    0 => {#890
  +"type": "dict_type"
  +"loc": array:1 [
    0 => "body"
  ]
  +"msg": "Input should be a valid dictionary"
  +"input": "{"test":"No","fields":"X"}"
  +"url": "https://errors.pydantic.dev/2.2/v/dict_type"
    }
  ]
}

期望读取数组中包含的字典。

python php fastapi
1个回答
0
投票

input_data 以字符串形式传入

"{"test":"No","fields":"X"}"

您可以使用

Pydantic
将其转换为字典。

import json
from pydantic import BaseModel, field_validator


class InputData(BaseModel):
     input_data: dict

    @field_validator("input_data", mode='before')
    def sanitize_dict(cls, v):
        return json.loads(v)

然后在你的 API 路径中

async def post(input_data:InputData):
   ```Your endpoint implementation here...```
© www.soinside.com 2019 - 2024. All rights reserved.