'Value Error Missing when using POST with FastAPI
I'm building a simple API with FastAPI using the official documentation, but when I try to test it with postman I get the same error:
pydantic.error_wrappers.ValidationError
Here is my model:
class Owner(BaseModel):
name: str
address: str
status: int
My endpoint:
@app.post('/api/v1/owner/add', response_model=Owner)
async def post_owner(owner: Owner):
return conn.insert_record(settings.DB_TABLE_OWN, owner)
And my method to insert it to the database (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'}
This is the JSON I send using postman:
{
"name": "Test",
"address": "Test address",
"status": 0
}
The error I get is the following:
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)
I gotta say that it was running fine until I stopped the server and got it running again.
Hope you can help me!
Solution 1:[1]
You have set the response_model=Owner which results in FastAPI to validate the response from the post_owner(...) route. Most likely, the
conn.insert_record(...) is not returning a response as the Owner model.
Solutions
- Change
response_modelto an appropriate one - Remove
response_model
Solution 2:[2]
Import List from typing module:
from typing import List
then change response_model=Owner to response_model=List[Owner]
Solution 3:[3]
@app.post('/api/v1/owner/add', response_model=Owner) def post_owner(owner: Owner): conn.insert_record(settings.DB_TABLE_OWN, owner) return owner
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JPG |
| Solution 2 | S.B |
| Solution 3 | Timsmall |
