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

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…

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

>Solution :

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.

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