Home > OS >  Fastapi custom response model
Fastapi custom response model

Time:10-10

I have a router that fetch all data from database. Here is my code:

@router.get('/articles/', response_model=List[articles_schema.Articles])
async def main_endpoint():
    query = articles_model.articles.select().where(articles_model.articles.c.status == 2)
    return await db.database.fetch_all(query)

The response is an array contains json object like this

[
    {
        "title": "example1",
        "content": "example_content1"
    },
    {
        "title": "example2",
        "content": "example_content2"
    },
]

But I want to make the response like this:

{
    "items": [
        {
            "title": "example1",
            "content": "example_content1"
        },
        {
            "title": "example2",
            "content": "example_content2"
        },
    ]
}

How can I achieve that? Please help. Thank you in advance

CodePudding user response:

You could simply define another model containing the items list as a field:

from pydantic import BaseModel
from typing import List

class ResponseModel(BaseModel):
    items: List[articles_schema.Articles]

and use it in the response:

@router.get('/articles/', response_model=ResponseModel)
async def main_endpoint():
    query = articles_model.articles.select().where(
        articles_model.articles.c.status == 2
    )
    return ResponseModel(
        items=await db.database.fetch_all(query),
    )
  • Related