Home > front end >  pydantic.error_wrappers.ValidationError : value is not a valid list (type=type_error.list)
pydantic.error_wrappers.ValidationError : value is not a valid list (type=type_error.list)

Time:10-07

New to FastAPI


Getting a "value is not a valid list (type=type_error.list)" error

Whenever I try to return {"posts": post}

@router.get('', response_model = List[schemas.PostResponseSchema])
def get_posts(db : Session = Depends(get_db)):
 print(limit)
 posts = db.query(models.Post).all()
 return {"posts" : posts}

Although it works if I return posts like this:

return posts

Here is my response model:

class PostResponseSchema(PostBase):
 user_id: int
 id: str
 created_at : datetime
 user : UserResponseSchema

 class Config:
     orm_mode = True

And Model:

class Post(Base):
 __tablename__ = "posts"
 id =  Column(Integer, primary_key=True, nullable=False)
 title = Column(String, nullable=False)
 content = Column(String, nullable = False)
 published = Column(Boolean, server_default = 'TRUE' , nullable = False)
 created_at = Column(TIMESTAMP(timezone=True), nullable = False, server_default = 
  text('now()'))
 user_id = Column(Integer, ForeignKey("users.id", ondelete = "CASCADE"), nullable = 
  False )

 user = relationship("User")

what am I missing here?

CodePudding user response:

your response expects to be the list by this line of code of yours:

@router.get('', response_model = List[schemas.PostResponseSchema])

but your response return {"posts" : posts} is object.

so you have to return posts because it is a list of objects as your response expects. otherwise, if you want to use return {"posts": posts} just change router.get('', response_model = List[schemas.PostResponseSchema]) to router.get('') then you will get something like this:

{"posts": [......]}

inside [] will be a list of posts.

  • Related