Search code examples
pythonpydantic

How to model an empty dictionary in pydantic


I'm working with a request of a remote webhook where the data I want to validate is either there, or an empty dictionary. I would like it to run through the model validator if it's there but also not choke if it's an empty dictionary.

input 1:

{
   "something": {}
}

input 2:

{
    "something": {
        "name": "George",
    }
}

input 3:

{
    "something": {
        "invalid": true
    }
}
class Person(BaseModel):
    name: str

class WebhookRequest(BaseModel):
    something: Union[Person, Literal[{}]]  # invalid literal

How would I model something like this in Pydantic such that inputs 1 and 2 succeed while input 3 fails?


Solution

  • Use extra = "forbid" option to disallow extra fields and use an empty model to represent an empty dictionary.

    from pydantic import BaseModel, ConfigDict
    
    
    class Empty(BaseModel):
        ...
    
        model_config = ConfigDict(extra="forbid")
    
    
    
    class Person(BaseModel):
        name: str
    
        model_config = ConfigDict(extra="forbid")
    
    
    class WebhookRequest(BaseModel):
        something: Person | Empty
    
        model_config = ConfigDict(extra="forbid")