'Pydantic validation error field required in FastAPI

In FastAPI app I got this error while trying to fetch data by this endpoint:

@app.get(
    "/users/{telegram_id}",
    response_model=schemas.UserBase,
    tags=["user"],
    status_code=status.HTTP_200_OK,
)
def read_user(telegram_id: int, db: Session = Depends(get_db)):
    """Read user by telegram id."""
    db_user = crud.get_user(db, user_telegram_id=telegram_id)
    if db_user is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
        )
    return db_user

Router is:

def get_user(db: Session, user_telegram_id: int):
    """GEt user by telegram id."""
    return (
        db.query(models.User)
        .filter(models.User.telegram_id == user_telegram_id)
        .first()
    )

Schemas are:

class UserArticlesSentView(BaseModel):
    """What fields will be in nested sent_articles list."""

    id: int
    # sent_articles: List[ArticleSentView] = []

    class Config:
        """Enable ORM mode."""

        orm_mode = True

class UserBase(BaseModel):
    """Base serializer for a user."""

    id: int
    telegram_id: int = Field(..., ge=0)
    username: str = Field(..., max_length=50)
    pet_name: str = Field(..., max_length=50)
    language_code: str = Field(..., max_length=3, min_length=2)
    sent_articles: List[UserArticlesSentView] = []

    class Config:
        """Enable ORM mode for all child methods."""

        orm_mode = True

UserBase pydantic model contains sent_articles field that must have a list of dicts with "id": value.

A validation error is:

pydantic.error_wrappers.ValidationError: 2 validation errors for UserBase
response -> sent_articles -> 0 -> id
  field required (type=value_error.missing)
response -> sent_articles -> 1 -> id
  field required (type=value_error.missing)

This error causes field "sent_articles" in UserBase schema. I do not understand why.

My models.py

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    telegram_id = Column(Integer, unique=True, index=True)
    username = Column(String(50))
    pet_name = Column(String(50))
    language_code = Column(String(5))

    sent_articles = relationship("Log", back_populates="sent_to_user")


class Article(Base):
    __tablename__ = "articles"

    id = Column(Integer, primary_key=True, index=True)
    text = Column(String(1024))
    image_url = Column(String(500))
    language_code = Column(String(255), index=True)

    sent_to_user = relationship("Log", back_populates="sent_articles")


class Log(Base):
    __tablename__ = "sent_log"

    user_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
    sent_to_user = relationship("User", back_populates="sent_articles")

    article_id = Column(Integer, ForeignKey("articles.id"), primary_key=True)
    sent_articles = relationship("Article", back_populates="sent_to_user")

    sent_time = (Column(DateTime(), server_default=text("NOW()")))

How to solve it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source