[Python] How do I correctly nest Pydantic models in a FastAPI response?

Discussão em 'Python' iniciado por Stack, Agosto 3, 2025.

  1. Stack

    Stack Membro Participativo

    The example code is below. Seems like when I nest two models, the nested models don't show up in the response even though the app can prove that the data is there. See the example below.

    Feels like I'm just doing something fundamentally wrong, but this doesn't seem like a wrong pattern to adopt, especially when the other parts seem to be just fine as is.

    #!/usr/bin/env python3

    from fastapi import FastAPI
    from pydantic import BaseModel

    class APIResponse(BaseModel):
    status: str
    data: BaseModel | None = None

    class APIData(BaseModel):
    name: str
    count: int

    app = FastAPI()
    @app.get('/')
    async def get_root():
    data = APIData(name="foo", count=1)
    response = APIResponse(status="success", data=data)

    print(data)
    ''' name='foo' count=1 '''
    print(response)
    ''' status='success' data=APIData(name='foo', count=1) '''

    return data
    ''' Returns {"name":"name_value","count":1} '''

    return response
    '''
    Expected {"status": "success", "data": {"name":"foo","count":1}}
    Actual {"status":"success","data":{}}
    '''

    Continue reading...

Compartilhe esta Página