I have the following models:
from pydantic import BaseModel
class A(BaseModel):
tag: str
field1: str
class B(BaseModel):
tag: str
field1: str
field2: str
I am using them to define the request body like so:
@app.post('/route')
def handle(request: typing.Union[A, B])
The documentation states:
include the most specific type first, followed by the less specific type
But I was wondering if there was a way I could guide FastAPI to select the correct model based on the tag. Currently, all of my models have a constant tag (i.e. type A
always has tag = 'A'
). Is there a way I can change my model definition to ensure that the assigned model always matches the tag received in the request body?
Currently, I am getting around this by not typing my handle
function, and instead specifically matching the tag
to the model, but ideally I would just use typing.Union
as the type and be confident it is getting it correct.