[英]FastAPI POST - Error 422 detail'': ( ( loc'':(body file msg'':field required'', type'': value_error missing)))
[英]Value Error Missing when using POST with FastAPI
我正在使用官方文檔使用 FastAPI 構建一個簡單的 API,但是當我嘗試使用郵遞員對其進行測試時,我得到了同樣的錯誤:
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(...)
沒有作為Owner模型返回響應。
response_model
更改為適當的response_model
從typing
模塊導入List
:
from typing import List
然后將response_model=Owner
更改為response_model=List[Owner]
@app.post('/api/v1/owner/add', response_model=Owner) def post_owner(owner: Owner): conn.insert_record(settings.DB_TABLE_OWN, owner) return owner
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.