小编LJG*_*LJG的帖子

如何在 FastAPI 中 POST 具有单个主体参数的 JSON?

我有一个名为的文件main.py,其中POST仅使用一个输入参数(整数)进行调用。简化代码如下:

from fastapi import FastAPI

app = FastAPI()

@app.post("/do_something/")
async def do_something(process_id: int):
    # some code
    return {"process_id": process_id}
Run Code Online (Sandbox Code Playgroud)

现在,如果我运行保存在文件中的测试代码test_main.py,即:

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_do_something():
    response = client.post(
        "/do_something/",
        json={
            "process_id": 16
        }
    )
    return response.json()

print(test_do_something())
Run Code Online (Sandbox Code Playgroud)

我得到:

{'detail': [{'loc': ['query', 'process_id'], 'msg': 'field required', 'type': 'value_error.missing'}]}
Run Code Online (Sandbox Code Playgroud)

我不明白这是什么错误。有必要继续呼吁POST

python fastapi

7
推荐指数
1
解决办法
8492
查看次数

定义 Pydantic(嵌套)模型

如果我使用 GET (给定一个 id),我会得到一个 JSON,如下所示:

{
    "data": {
        "id": "81",
        "ks": {
            "k1": 25,
            "k2": 5
        },
        "items": [
            {
                "id": 1,
                "name": "John",
                "surname": "Smith"
            },
            {
                "id": 2,
                "name": "Jane",
                "surname": "Doe"
            }
        ]
    },
    "server-time": "2021-12-09 14:18:40"
}
Run Code Online (Sandbox Code Playgroud)

对于特定情况(如果 id 不存在):

{
    "data": {
        "id": -1,
        "ks": "",
        "items": []
    },
    "server-time": "2021-12-10 09:35:22"
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个 Pydantic 模型来管理这个数据结构(我的意思是正式定义这些对象)。通过创建类(可能是嵌套的)来管理此数据结构的最明智的方法是什么?

python json pydantic fastapi

5
推荐指数
2
解决办法
3万
查看次数

标签 统计

fastapi ×2

python ×2

json ×1

pydantic ×1