我有一个名为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}
现在,如果我运行保存在文件
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())
我理解为:
{'detail': [{'loc': ['query', 'process_id'], 'msg': 'field required', 'type': 'value_error.missing'}]}
我无法弄清楚错误在哪里。必须保持调用方式为POST
。
async def do_something_else(items: List[Dict], process_id: int = Body(...))
,并在调用时使用client.post("/do_something_else/", json={"process_id": ..., "items": [{...}, {...}]})
。 - LJGBody(...)
将不起作用。 - LJG