Replies: 3 comments 4 replies
-
Looks like a FastAPI bug. |
Beta Was this translation helpful? Give feedback.
-
Would model_dump help here? |
Beta Was this translation helpful? Give feedback.
-
Hey! I think docs generation breaks because FastAPI doesn't generate a definition for union types. So they don't have a I found a workaround: from typing import Annotated, Literal
from fastapi import FastAPI
from pydantic import BaseModel, Field, RootModel
class BlackCat(BaseModel):
pet_type: Literal['cat']
color: Literal['black']
black_name: str
class WhiteCat(BaseModel):
pet_type: Literal['cat']
color: Literal['white']
white_name: str
class Cat(RootModel[Annotated[BlackCat | WhiteCat, Field(discriminator='color')]]): ...
class Dog(BaseModel):
pet_type: Literal['dog']
name: str
Pet = Annotated[Cat | Dog, Field(discriminator='pet_type')]
class Model(BaseModel):
pet: Pet
n: int
app = FastAPI()
@app.get('/', response_model=Model)
async def root():
model = Model(pet={'pet_type': 'cat', 'color': 'black', 'black_name': 'felix'}, n=1)
return model There we use |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
/docs
or/redoc
. It should generate documentation and return it, but instead it returnsOperating System
macOS
Operating System Details
No response
FastAPI Version
0.109.0
Pydantic Version
2.6.0
Python Version
3.11.6
Additional Context
There is an Open issue for Pydantic.
However, just dumping the model to JSON works for me.
output
Beta Was this translation helpful? Give feedback.
All reactions