Getting validation error with FastAPI after updating response model

46 Views Asked by At

I'm facing error 500 when calling endpoints that used to work... I only updated the response model to output a new column called "owner_id" linked to the id of another table (with foreign key)

Here is my API router example:

@router.get("/", response_model=List[schemas.Post]) #we should return a list of posts
def get_posts(db : Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)):
    posts = db.query(models.Post).all() 
    return posts

This is the response model class:

class PostBase(BaseModel):
    title : str
    content : str
    published : bool = True


class CreatePost(PostBase):
    pass


# Pydantic model for the response
class Post(PostBase):
    id : int
    created_at : datetime
    owner_id : int

    #to make sure it converts to dict() - see doc
    class Config:
        from_attributes = True

And finally in case sqlalchemy table creation can help:

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, default=True)
    owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
    created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, nullable=False)
    email = Column(String, nullable=False, unique=True) #unique to avoid same email to registe twice
    password = Column(String, nullable=False)
    created_at = Column(TIMESTAMP(timezone=True), nullable=False, server_default=text('now()'))

All my endpoints are built the same way and used to work before I start working with foreign key and update the response model to retrieve the new column

EDIT: It seems I can get rid of this error by referencing BaseModel in my response class instead of PostBase (inheritance) Still, does not explain why it suddenly stopped working

Thank you

0

There are 0 best solutions below