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:
JavaScript
x
4
1
{
2
"something": {}
3
}
4
input 2:
JavaScript
1
6
1
{
2
"something": {
3
"name": "George",
4
}
5
}
6
input 3:
JavaScript
1
6
1
{
2
"something": {
3
"invalid": true
4
}
5
}
6
JavaScript
1
6
1
class Person(BaseModel):
2
name: str
3
4
class WebhookRequest(BaseModel):
5
something: Union[Person, Literal[{}]] # invalid literal
6
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.
JavaScript
1
23
23
1
from pydantic import BaseModel
2
3
4
class Empty(BaseModel):
5
6
7
class Config:
8
extra = "forbid"
9
10
11
class Person(BaseModel):
12
name: str
13
14
class Config:
15
extra = "forbid"
16
17
18
class WebhookRequest(BaseModel):
19
something: Person | Empty
20
21
class Config:
22
extra = "forbid"
23