Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a list type in FastAPI response?

My objective is return a list of tags as response.

I have a Tag schema like this in my FastAPI app:

class Tag(BaseModel):
    nome: str

    class Config:
        from_attributes = True


class TagList(BaseModel):
    tags: List[Tag] = []

    class Config:
        from_attributes = True

I wanted return the following response:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "tags": ["t1", "t2", "t3"]
}

However, i get the following:

{
  "tags": [
    {
      "name": "t1"
    },
    {
      "name": "t2"
    },
    {
      "name": "t3"
    }
  ]
}

This is my endpoint:

@router.get('/tags', response_model=TagList, status_code=200)
def read_tools(db: Session = Depends(get_session)):
    with db as session:
        query = """
            select 
            name
            from tags
        """
        result = session.execute(text(query))
        tags = [r for r in result]
    return {'tags': tags}

>Solution :

Return only tag names instead of full Tag objects, you can modify the read_tools function as follows:

@router.get('/tags', response_model=dict, status_code=200)
def read_tools(db: Session = Depends(get_session)):
    with db as session:
        query = """
            select 
            name
            from tags
        """
        result = session.execute(text(query))
        tags = [row[0] for row in result]  # Extracting only the tag names from the query result
    return {'tags': tags}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading