Fastapi Pydantic | ‘Input should be a valid dictionary or object to extract fields from’

I’m using @model_validator along with model_validate to check if values match child class:

sample request payload:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"name": "BC",
"connectorType": "SNOWFLAKE",
"productName": "bc",
"secretArn": "foobararn",
"warehouse": "foobarwarehouse",
"tableSchema": "foobarschema",
"database": "bardatabse"
}
</code>
<code>{ "name": "BC", "connectorType": "SNOWFLAKE", "productName": "bc", "secretArn": "foobararn", "warehouse": "foobarwarehouse", "tableSchema": "foobarschema", "database": "bardatabse" } </code>
{
  "name": "BC",
  "connectorType": "SNOWFLAKE",
  "productName": "bc",
  "secretArn": "foobararn",
  "warehouse": "foobarwarehouse",
  "tableSchema": "foobarschema",
  "database": "bardatabse"

}

Snowflake connector class:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class SnowflakeConnector(SpotApiBaseModel):
"""Snowflake Connector."""
model_config = ConfigDict(from_attributes=True)
secretArn: str = Field(description="AWS secret arn")
warehouse: str = Field(description="Snowflake warehouse. Required for connector type: SNOWFLAKE")
database: str = Field(description="Database name. Required for connector type: SNOWFLAKE")
tableSchema: str = Field(description="Database table schema. Required for connector type: SNOWFLAKE")
class ConnectorInterface(BaseConnector):
@model_validator(mode='before')
def check_allowed_products(cls, values):
connector = values.get('connectorType').lower()
if connector == "s3":
S3Connector.model_validate(values)
elif connector == "snowflake":
SnowflakeConnector.model_validate(values)
</code>
<code>class SnowflakeConnector(SpotApiBaseModel): """Snowflake Connector.""" model_config = ConfigDict(from_attributes=True) secretArn: str = Field(description="AWS secret arn") warehouse: str = Field(description="Snowflake warehouse. Required for connector type: SNOWFLAKE") database: str = Field(description="Database name. Required for connector type: SNOWFLAKE") tableSchema: str = Field(description="Database table schema. Required for connector type: SNOWFLAKE") class ConnectorInterface(BaseConnector): @model_validator(mode='before') def check_allowed_products(cls, values): connector = values.get('connectorType').lower() if connector == "s3": S3Connector.model_validate(values) elif connector == "snowflake": SnowflakeConnector.model_validate(values) </code>
class SnowflakeConnector(SpotApiBaseModel):
    """Snowflake Connector."""
    model_config = ConfigDict(from_attributes=True)

    secretArn: str = Field(description="AWS secret arn")
    warehouse: str = Field(description="Snowflake warehouse. Required for connector type: SNOWFLAKE")
    database: str = Field(description="Database name. Required for connector type: SNOWFLAKE")
    tableSchema: str = Field(description="Database table schema. Required for connector type: SNOWFLAKE")


class ConnectorInterface(BaseConnector):

    @model_validator(mode='before')
    def check_allowed_products(cls, values):
        connector = values.get('connectorType').lower()
        if connector == "s3":
            S3Connector.model_validate(values)
        elif connector == "snowflake":
            SnowflakeConnector.model_validate(values)

When any of the required fields is missing I’m getting expected response:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"Field required: ('body', 'database')"
</code>
<code>"Field required: ('body', 'database')" </code>
"Field required: ('body', 'database')"

but when all fields are there, instead of getting correct response I’m getting this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>"Input should be a valid dictionary or object to extract fields from: ('body',)"
</code>
<code>"Input should be a valid dictionary or object to extract fields from: ('body',)" </code>
"Input should be a valid dictionary or object to extract fields from: ('body',)"

Exception:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{"time": "2024-06-18T10:46:45.641Z", "l": "ERROR", "rid": "2558770a-66ff-4da0-b8a2-977afc5043e6", "org": "", "act": "", "message": "An error occurred: [{'type': 'model_attributes_type', 'loc': ('body',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': None, 'url': 'https://errors.pydantic.dev/2.6/v/model_attributes_type'}]", "component": {"name": "/app/common/exceptions/base_exception_handler.py", "version": "0.1.3"}, "exception": "Traceback (most recent call last):n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 68, in __call__n await self.app(scope, receive, sender)n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__n raise en File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__n await self.app(scope, receive, send)n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 718, in __call__n await route.handle(scope, receive, send)n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 276, in handlen await self.app(scope, receive, send)n File "Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 66, in appn response = await func(request)n ^^^^^^^^^^^^^^^^^^^n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/routing.py", line 273, in appn raise RequestValidationError(_normalize_errors(errors), body=body)nfastapi.exceptions.RequestValidationError: [{'type': 'model_attributes_type', 'loc': ('body',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': None, 'url': 'https://errors.pydantic.dev/2.6/v/model_attributes_type'}]"}
</code>
<code>{"time": "2024-06-18T10:46:45.641Z", "l": "ERROR", "rid": "2558770a-66ff-4da0-b8a2-977afc5043e6", "org": "", "act": "", "message": "An error occurred: [{'type': 'model_attributes_type', 'loc': ('body',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': None, 'url': 'https://errors.pydantic.dev/2.6/v/model_attributes_type'}]", "component": {"name": "/app/common/exceptions/base_exception_handler.py", "version": "0.1.3"}, "exception": "Traceback (most recent call last):n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 68, in __call__n await self.app(scope, receive, sender)n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__n raise en File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__n await self.app(scope, receive, send)n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 718, in __call__n await route.handle(scope, receive, send)n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 276, in handlen await self.app(scope, receive, send)n File "Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 66, in appn response = await func(request)n ^^^^^^^^^^^^^^^^^^^n File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/routing.py", line 273, in appn raise RequestValidationError(_normalize_errors(errors), body=body)nfastapi.exceptions.RequestValidationError: [{'type': 'model_attributes_type', 'loc': ('body',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': None, 'url': 'https://errors.pydantic.dev/2.6/v/model_attributes_type'}]"} </code>
{"time": "2024-06-18T10:46:45.641Z", "l": "ERROR", "rid": "2558770a-66ff-4da0-b8a2-977afc5043e6", "org": "", "act": "", "message": "An error occurred: [{'type': 'model_attributes_type', 'loc': ('body',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': None, 'url': 'https://errors.pydantic.dev/2.6/v/model_attributes_type'}]", "component": {"name": "/app/common/exceptions/base_exception_handler.py", "version": "0.1.3"}, "exception": "Traceback (most recent call last):n  File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/middleware/exceptions.py", line 68, in __call__n    await self.app(scope, receive, sender)n  File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/middleware/asyncexitstack.py", line 20, in __call__n    raise en  File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/middleware/asyncexitstack.py", line 17, in __call__n    await self.app(scope, receive, send)n  File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 718, in __call__n    await route.handle(scope, receive, send)n  File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 276, in handlen    await self.app(scope, receive, send)n  File "Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/starlette/routing.py", line 66, in appn    response = await func(request)n               ^^^^^^^^^^^^^^^^^^^n  File "/Library/Caches/pypoetry/virtualenvs/service-Qx3_L5c2-py3.12/lib/python3.12/site-packages/fastapi/routing.py", line 273, in appn    raise RequestValidationError(_normalize_errors(errors), body=body)nfastapi.exceptions.RequestValidationError: [{'type': 'model_attributes_type', 'loc': ('body',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': None, 'url': 'https://errors.pydantic.dev/2.6/v/model_attributes_type'}]"}

model validated and request proceed rest of the logic

New contributor

electromecca is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật