Skip to content

Union produces anyOf instead of oneOf for OpenAPI generation #4959

@stdkoehler

Description

@stdkoehler

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from typing import Literal, Union
from pydantic import BaseModel, Field


class Cat(BaseModel):
    pet_type: Literal['cat']
    meows: int


class Dog(BaseModel):
    pet_type: Literal['dog']
    barks: float


class Pet(BaseModel):
    __root__: Union[Cat, Dog] = Field(..., discriminator='pet_type')

Pet.schema_json()

Description

Hi all,

Example from https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions:

Using the class Pet above in FastAPI to allow either Cat or Dog as an input leads to an OpenAPI.json which makes Pet like (printed as yaml)

Pet:
  anyOf:
  - $ref: '#/components/schemas/Cat'
  - $ref: '#/components/schemas/Dog'
  
  discriminator:
    propertyName: pet_type

both OpenApi (https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/) and the specification https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#discriminatorObject linked by the pydantic docs (link on top) state that it should be oneOf.

I think it's a pydantic issue, But there was already an issue for pydantic which was closed without resolve:
pydantic/pydantic#656
So I open it here, because it may be more relevant for FastAPI, since it leads to an incorrect OpenAPI file. Let me know if you think differently.

Best
Stefan

Operating System

Linux, Windows

Operating System Details

No response

FastAPI Version

0.75.0

Python Version

Python 3.9.7

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions