I have a JSON field (form_config) in Postgres table which contains form field structure. This is the value in that table.
[
{
'label': 'Age',
'type': 'number',
'required': True,
'min': 0,
'max': None
},
{
'label': 'Name',
'type': 'text',
'required': True,
'minLength': 0,
'maxLength': None
},
{
'label': 'City',
'type': 'autocomplete',
'required': True,
'api': {
'url': 'api/countries',
'method': 'GET',
'labelKey': 'name'
}
}
]
There is an API which fetches above data, and it returns based on Response Schema as below:
class FormConfigResponse(BaseModel):
config : List[FormFieldModel]
where Form Field schema are as follows, using discriminator:
class FormFieldType(str, Enum):
text = 'text'
number = 'number'
autocomplete= 'autocomplete'
class FormFieldBase(BaseModel):
label: str
type: FormFieldType
required: bool = True
class TextField(FormFieldBase):
type: Literal[FormFieldType.text] = FormFieldType.text
minLength: int|None
maxLength: int|None
class NumberField(FormFieldBase):
type: Literal[FormFieldType.number] = FormFieldType.number
min: int|None
max: int|None
class APIAutoCompleteConfig(BaseModel):
url: str
method: str
labelKey: str
class AutoCompleteField(FormFieldBase):
type: Literal[FormFieldType.autocomplete] = FormFieldType.autocomplete
api: APIAutoCompleteConfig
# Create a new model to represent the discriminated union
FormFieldModel = Annotated[Union[NumberField, TextField, AutoCompleteField], Field(discriminator='type')]
In my API handler code, when it returns the data as follows:
return FormConfigResponse(
config = form_config
)
I get an error like so:
fastapi_app | content = await serialize_response(
fastapi_app | File "/usr/local/lib/python3.10/site-packages/fastapi/routing.py", line 155, in serialize_response
fastapi_app | raise ResponseValidationError(
fastapi_app | fastapi.exceptions.ResponseValidationError: 1 validation errors:
fastapi_app | {'type': 'model_attributes_type', 'loc': ('response', 'config'), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': [NumberField(label='Age', type=<FormFieldType.number: 'number'>, required=True, min=0, max=None), TextField(label='Name', type=<FormFieldType.text: 'text'>, required=True, minLength=0, maxLength=None), AutoCompleteField(label='City', type=<FormFieldType.autocomplete: 'autocomplete'>, required=True, api=APIAutoCompleteConfig(url='api/countries', method='GET', labelKey='name'))], 'url': 'https://errors.pydantic.dev/2.8/v/model_attributes_type'}
It’s saying “Input should be a valid dictionary or object to extract fields from”. Where am I going wrong?