diff --git a/fastapi/_compat/v2.py b/fastapi/_compat/v2.py index c913874612..2dabdc69c1 100644 --- a/fastapi/_compat/v2.py +++ b/fastapi/_compat/v2.py @@ -585,10 +585,10 @@ if shared.PYDANTIC_VERSION_MINOR_TUPLE >= (2, 6): # Omit by default for scalar mapping and scalar sequence mapping annotations # added in Pydantic v2.6 https://github.com/pydantic/pydantic/releases/tag/v2.6.0 def _omit_by_default(annotation: Any) -> Any: - origin = getattr(annotation, "__origin__", None) - args = getattr(annotation, "__args__", ()) + origin = get_origin(annotation) + args = get_args(annotation) - if origin is Union: + if origin is Union or origin is UnionType: new_args = tuple(_omit_by_default(arg) for arg in args) return Union[new_args] elif origin is list: diff --git a/tests/test_request_params/test_query/test_free_form.py b/tests/test_request_params/test_query/test_free_form.py index d2f28bd952..a0fd28aaa5 100644 --- a/tests/test_request_params/test_query/test_free_form.py +++ b/tests/test_request_params/test_query/test_free_form.py @@ -1,4 +1,4 @@ -from typing import Annotated +from typing import Annotated, Union import pytest from dirty_equals import IsOneOf @@ -82,7 +82,7 @@ def test_required_dict_str(path: str): @app.get("/required-dict-union") async def read_required_dict_union( - p: Annotated[dict[str, str] | dict[str, int], Query()], + p: Annotated[Union[dict[str, str], dict[str, int]], Query()], ): return {"p": p}