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