Erika
Erika

Reputation: 161

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!

Upvotes: 5

Views: 5951

Answers (3)

Timsmall
Timsmall

Reputation: 1

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

Upvotes: 0

Rasanga srimal
Rasanga srimal

Reputation: 21

Import List from typing module:

from typing import List

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

Upvotes: 1

JPG
JPG

Reputation: 88429

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

Upvotes: 7

Related Questions