5

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!

Erika
  • 151
  • 3
  • 12

3 Answers3

7

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

  1. Change response_model to an appropriate one
  2. Remove response_model
JPG
  • 82,442
  • 19
  • 127
  • 206
1

Import List from typing module:

from typing import List

then change response_model=Owner to response_model=List[Owner]

S.B
  • 13,077
  • 10
  • 22
  • 49
0

@app.post('/api/v1/owner/add', response_model=Owner) def post_owner(owner: Owner): conn.insert_record(settings.DB_TABLE_OWN, owner) return owner

Timsmall
  • 1
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 18 '22 at 12:05