sending a list value in a Post request's body to validate Pydantic model

Viewed 10038

I'm using FastAPI, Pydantic, SQLAlchemy, and Postgres to build a service that receives post requests and stores the data on the database. There is a List in the Pydantic model like the following:

from typing import List
from pydantic import BaseModel, Field

class Note(base model):
    id: int
    title: str
    authors: List[str]

And the table:

notes = Table(
    "notes",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("title", String),
    Column("authors", ARRAY(String(50), dimensions=3)),
)

Here is the way I do the post request, when there is not a List value:

def post(payload: Note):
    query = questions.insert().values(title=payload.title)
    return database.execute(query=query)

Post request's body:

{
    "title": "some value"
}

And it works fine. But adding the List value breaks it with Pydantic's validation error:

def post(payload: Note):
    query = questions.insert().values(title=payload.title, authors=payload.authors)
    return database.execute(query=query)
{
    "title": "some value",
    "authors": ["name1", "name2", "name3"]
}

value is not a valid list

type_error.list

How can I change the post function and request body, to make this work?

Edit: The traceback:

ERROR:    Exception in ASGI application
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/usr/lib/python3/dist-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/applications.py", line 149, in __call__
    await super().__call__(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/applications.py", line 102, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 550, in __call__
    await route.handle(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
    await self.app(scope, receive, send)
  File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
    response = await func(request)
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 204, in app
    response_data = await serialize_response(
  File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 126, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Note
response
  value is not a valid list (type=type_error.list)
3 Answers

I figured this out. The problem resolved by fixing the respone_model that has an error, and all I was doing for storing the data was correct.

@router.post("/", response_model=Note, status_code=201)
def create_note(payload: Note):
    note_id = post(payload)
    response_object = {
        "id": note_id,
        "title": payload.title,
        "authors": payload.authors,
    }
    return response_object
@router.get("/fetchusuarios", response_model=List[providers.schemas.User])
async def fetchall_users(db:Session=Depends(get_db)):
    usuarios = db.query(models.usermodel.User).all()
    return usuarios

I was using Django-Ninja (based on FastAPI) and had the same error. Originally, my decorator was like this:

@router.get('/apartment-sale-hanoi/', response=List[ApartmentSaleHanoiSchema])

I fixed value is not a valid list (type=type_error.list) just by removing List from the response model as following:

@router.get('/apartment-sale-hanoi/', response=ApartmentSaleHanoiSchema)

my returning response (displayed as JSON) was a list of objects

response = ApartmentSaleHanoi.objects.all()
Related