我正在使用官方文档用FastAPI构建一个简单的API,但当我试图用poster测试它时,我得到了相同的错误:
pydantic.error_wrappers.ValidationError
这是我的型号:
class Owner(BaseModel):
name: str
address: str
status: int
我的终点:
@app.post('/api/v1/owner/add', response_model=Owner)
async def post_owner(owner: Owner):
return conn.insert_record(settings.DB_TABLE_OWN, owner)
以及我将其插入数据库的方法(RethinkDB(
@staticmethod
def insert_record(table, record):
try:
return DBConnection.DB.table(table).insert(record.json()).run()
except RqlError:
return {'Error': 'Could not insert record'}
这是我使用邮递员发送的JSON:
{
"name": "Test",
"address": "Test address",
"status": 0
}
我得到的错误如下:
pydantic.error_wrappers.ValidationError: 3 validation errors for Owner
response -> name
field required (type=value_error.missing)
response -> address
field required (type=value_error.missing)
response -> status
field required (type=value_error.missing)
我不得不说它运行得很好,直到我停止服务器并重新运行。
希望你能帮助我!
您已经设置了response_model=Owner
,这将导致FastAPI验证post_owner(...)
路由的响应。很可能conn.insert_record(...)
不会作为所有者模型返回响应。
解决方案
- 将
response_model
更改为适当的 - 删除
response_model
从typing
模块导入List
:
from typing import List
则将response_model=Owner
更改为response_model=List[Owner]
@app.post('/api/v1/owner/add',response_mode=owner(def post_owner(所有者:所有者(:conn.insert_record(settings.DB_ABLE_OWN,所有者(退货所有者