如何在FastAPI响应中返回列表类型?

0 投票
1 回答
37 浏览
提问于 2025-04-12 20:23

我的目标是返回一个标签的列表作为响应。

在我的FastAPI应用中,我有一个这样的标签结构:

class Tag(BaseModel):
    nome: str

    class Config:
        from_attributes = True


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

    class Config:
        from_attributes = True

我想返回以下响应:

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

但是,我得到了以下内容:

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

这是我的接口:

@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}

1 个回答

0

如果你只想返回标签的名字,而不是完整的标签对象,可以这样修改read_tools这个函数:

@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}

撰写回答