Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of items in FastAPI response

In my Fast API app I have this pydantic model

class UserInArticleView(BaseModel):
    """What fields will be in nested sent_to_user list."""

    telegram_id: int

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

        orm_mode = True

class ArticleBase(BaseModel):
    id: int
    text: str = Field(..., min_length=50, max_length=1024)
    image_url: HttpUrl = Field(..., title="Image URL")
    language_code: str = Field("ru", max_length=3, min_length=2)
    sent_to_user: List[UserInArticleView] = []

    class Config:
        orm_mode = True

The response is

[
  {
    "id": 1,
    "text": "Some text",
    "image_url": "http://test.tt/",
    "language_code": "ru",
    "sent_to_user": [
      {
        "telegram_id": 444444444
      },
      {
        "telegram_id": 111111111
      }
    ]
  }
]

Is there a way to have a response with "sent_to_user" as a list of values, like below? The reason is I need to check IN condition.

"sent_to_user": [
  444444444,
  111111111
]

The final solution is:

@app.get("/articles/{article_id}", tags=["article"])
def read_article(article_id: int, db: Session = Depends(get_db)):
    """Read single article by id."""
    db_article = crud.get_article(db, article_id=article_id)
    if db_article is None:
        raise HTTPException(status_code=404, detail="Article not found")
    list_sent_to_user = [i.telegram_id for i in db_article.sent_to_user]
    print("list", list_sent_to_user)
    return list_sent_to_user
like image 203
Vitalii Mytenko Avatar asked Feb 02 '26 21:02

Vitalii Mytenko


1 Answers

To do this you can create a new pydantic model that extends your ArticleBase model and reassign the type of sent_to_user to a List of int and use this template for your response

class ArticleBase(BaseModel):
    id: int
    text: str = Field(..., min_length=50, max_length=1024)
    image_url: HttpUrl = Field(..., title="Image URL")
    language_code: str = Field("ru", max_length=3, min_length=2)
    sent_to_user: List[UserInArticleView] = []

    class Config:
        orm_mode = True


class ArticleResponse(ArticleBase):
    sent_to_user: List[int] = []

Then, you have to format your answer to fit the requested format:

list_int = [elt['telegram_id'] for elt in result_articles['sent_to_user']]

example integration:


@router.get('/articles/{article_id}',
    summary="get article"
    status_code=status.HTTP_200_OK,
    response_model=ArticleResponse)
def update_date(article_id:int):
   articles = get_article(article_id)
   articles.sent_to_user = [elt.telegram_id for elt in articles.sent_to_user]

   return articles

The code has not been really tested, it is only intended to give an idea of integration of the code provided

like image 132
fchancel Avatar answered Feb 04 '26 09:02

fchancel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!