Skip to content
Advertisement

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?

Advertisement

Answer

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

from pydantic import BaseModel


class Empty(BaseModel):
    ...

    class Config:
        extra = "forbid"


class Person(BaseModel):
    name: str

    class Config:
        extra = "forbid"


class WebhookRequest(BaseModel):
    something: Person | Empty

    class Config:
        extra = "forbid"
Advertisement