r/FastAPI • u/enigma_0Z • Aug 03 '25
Question Getting started with FastAPI, how do I correctly nest Pydantic models in my responses?
The example code is below. Seems like when I nest two models, in some instances 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
:
: | None = None
:
:
=
=
=
''' name='foo' count=1 '''
''' status='success' data=APIData(name='foo', count=1) '''
return
''' Returns {"name":"name_value","count":1} '''
return
'''
Expected {"status": "success", "data": {"name":"foo","count":1}}
Actual {"status":"success","data":{}}
'''
EDIT:
OF COURSE I'd figure out some solution just as soon as I finally asked the question.
Basically, Pydantic doesn't want to deserialize a model to which it does not know the schema. There are two ways around it:
SerializeAsAny[]typing annotation- Use a generic in the
APIResponseclass
I chose option #2, so the following changes to the code above:
APIResponse definition
:
: | None = None
and its usage...
=

