0

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

2
  • 2
    What is the error message? Commented Sep 6, 2023 at 15:26
  • Just added the error message down below Commented Sep 7, 2023 at 7:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.