Bhavya Sharma
Bhavya Sharma

Reputation: 67

response in list form: FastAPI

@app.get("/{subject}")
def getResult(subject:str, db:Session = Depends(get_db):
    quesnQuery = db.query(models.Post).filter(
        func.lower(models.Post.category) == func.lower(subject)
    ).order_by(func.random())
    quesn = quesnQuery.limit(10).all()
    return quesn

For code above I am getting the response in following form

0:[]

But I want the return statement to be in following format

response:[{},{},{},{},{}]

I am unable to achieve the desired response format. Is there a way to do so...

Upvotes: 0

Views: 159

Answers (1)

MatsLindh
MatsLindh

Reputation: 52862

The quick and dirty solution: return a dictionary mapping to your structure (this won't be documented properly):

return {
    "response": quesn,
}

The proper solution: create a set of Pydantic models that describe the schema of your response and use that to tell FastAPI how you want the response to be formatted:

from pydantic import BaseModel

class Post:
    title: str
    content: str
    category: str


class PostSubjectResponse(BaseModel):
    response: List[Post]


@app.get("/{subject}", response_model=PostSubjectResponse)
def get_posts_from_subject(subject: str, db: Session = Depends(get_db)):
    pass

This will result in the API endpoint being properly documented in the openapi spec as well.

Upvotes: 1

Related Questions