Description
When attempting to instantiate an instance of the Pydantic model BRDP using the deprecated parse_raw method, a validation error occurs when a dictionary object lacks a required field, specifically the event field. Despite event being defined as optional within the BRDP model, the parsing process expects this field to be present within the provided dictionary, causing a validation error.
The absence of the event field within the dictionary passed to parse_raw results in a validation error, although event is marked as optional within the BRDP model.
This issue affects processes that rely on parsing dictionaries into Pydantic models using the deprecated parse_raw method, causing unexpected validation errors when optional fields are missing.
from pydantic import BaseModel
from typing import Optional, Dict, Any
import json
class BRDP(BaseModel):
"""BRDP of YoLink API."""
code: str
desc: str
method: str
data: Dict[str, Any]
event: Optional[str] # 'event' field is marked as optional
# Sample JSON data missing the 'event' field
json_string = '''
{
"code": "000000",
"time": 1701414599470,
"msgid": 1701414599470,
"method": "Home.getGeneralInfo",
"desc": "Success",
"data": {"id": "53c5283d408d4e6aba799330fbeeeaa9"}
}
'''
# Attempt to create a BRDP object using the provided JSON data
try:
brdp = BRDP()
brdp.parse_raw(json_string)
print(brdp)
except Exception as e:
print(f"Validation error occurred: {e}")
"""
Error:
event
Field required [type=missing, input_value={}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.5/v/missing
""""
This is fixed by using:
brdp = BRDP.model_construct(**json.loads(json_string))
Need perms to open a PR.