I know a concept from Typescript called Discriminated unions. That's a thing where you put 2 struct (classes, etc) and the type is decided depending on a struct's values. I'm trying to achieve similar thing in FastAPI with Pydantic validation. There are two different request payloads that I can recieve. Whether it's one or another depends on accountType
variable. If it's creative
it should be validated by RegistrationPayloadCreative
and if it's brand
it should validate by RegistrationPayloadBrand
. How do I achieve this? Couldn't find any other solution.
The problem is that it either returns
unexpected value; permitted: 'creative' (type=value_error.const; given=brand; permitted=('creative',))
Or it doesn't work at all.
class RegistrationPayloadBase(BaseModel):
first_name: str
last_name: str
email: str
password: str
class RegistrationPayloadCreative(RegistrationPayloadBase):
accountType: Literal['creative']
class RegistrationPayloadBrand(RegistrationPayloadBase):
company: str
phone: str
vat: str
accountType: Literal['brand']
class A(BaseModel):
b: Union[RegistrationPayloadBrand, RegistrationPayloadCreative]
def main():
A(b={'first_name': 'sdf', 'last_name': 'sdf', 'email': 'sdf', 'password': 'sdfds', 'accountType': 'brand'})
if __name__ == '__main__':
main()