← baseline_full

fastapi_12942

failed NO_PATCH NO_PATCH UNSUBMITTED empty_patch(None) · None tool calls · 0 s · fastapi/fastapi

Task input

🐛 Fix tagged discriminated union not recognized as body field

## Problem

When using a union type models with a tagged discriminator as an endpoint parameter, like the following:

```py
class Pie(BaseModel):
    time_to_cook: int
    num_ingredients: int


class ApplePie(Pie):
    fruit: Literal["apple"] = "apple"


class PumpkinPie(Pie):
    filling: Literal["pumpkin"] = "pumpkin"


def get_discriminator_value(v: Any) -> str:
    if isinstance(v, dict):
        return v.get("fruit", v.get("filling"))
    return getattr(v, "fruit", getattr(v, "filling", None))


Dessert = Annotated[
    Annotated[ApplePie, Tag("apple")] | Annotated[PumpkinPie, Tag("pumpkin")],
    Discriminator(get_discriminator_value),
]


app = FastAPI()
@app.post("/dessert")
async def dinner(dessert: Dessert) -> dict[str, Any]:
    return dessert.model_dump()
```

FastAPI fails to identify it correctly as **body** payload. It incorrectly considers it's a query parameter, which then causes a validation error. The workaround currently is to explicitly tell FastAPI it's a body parameter using `dessert: Annotated[Dessert, Body()]`

## Fix

The solution is to improve the function handling type annotations by handling the case where we can have `Annotated`
 types inside an `Annotated` type.

---

Discussed in https://github.com/fastapi/fastapi/discussions/12941

Tool calls (0)

#ToolArgumentsResult
No trace captured.