How to return a list type in FastAPI response?

Question:

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:

{
  "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}
Asked By: Hidan

||

Answers:

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}
Answered By: jepozdemir
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.