fastapi-code-generator icon indicating copy to clipboard operation
fastapi-code-generator copied to clipboard

Discriminated union with simple types (str)

Open agoddijn-fern opened this issue 9 months ago • 0 comments

The following

Content:
      oneOf:
        - type: string
        - $ref: "#/components/schemas/ImageUrl"
        - $ref: "#/components/schemas/AudioUrl"
        - $ref: "#/components/schemas/DocumentUrl"
        - $ref: "#/components/schemas/BinaryContent"
      discriminator:
        propertyName: kind
        mapping:
          image_url: "#/components/schemas/ImageUrl"
          audio_url: "#/components/schemas/AudioUrl"
          document_url: "#/components/schemas/DocumentUrl"
          binary_content: "#/components/schemas/BinaryContent"
      description: Union type representing different content formats

Produces

class Content(RootModel[Union[str, ImageUrl, AudioUrl, DocumentUrl, BinaryContent]]):
    root: Union[str, ImageUrl, AudioUrl, DocumentUrl, BinaryContent] = Field(
        ...,
        description='Union type representing different content formats',
        discriminator='kind',
    )

Which is not supported by pydantic

exception=TypeError("'str' is not a valid discriminated union variant; should be a 'BaseModel' or 'dataclass'")

agoddijn-fern avatar Mar 19 '25 10:03 agoddijn-fern