{"id":"8693ca626d9c6114","repo":"tiangolo/fastapi","slug":"expected-uploadfile-received-type-input-value","errorCode":null,"errorMessage":"Expected UploadFile, received: {type(__input_value)}","messagePattern":"Expected UploadFile, received: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":422,"severity":"error","filePath":"fastapi/datastructures.py","lineNumber":135,"sourceCode":"\n        Any next read or write will be done from that position.\n\n        To be awaitable, compatible with async, this is run in threadpool.\n        \"\"\"\n        return await super().seek(offset)\n\n    async def close(self) -> None:\n        \"\"\"\n        Close the file.\n\n        To be awaitable, compatible with async, this is run in threadpool.\n        \"\"\"\n        return await super().close()\n\n    @classmethod\n    def _validate(cls, __input_value: Any, _: Any) -> \"UploadFile\":\n        if not isinstance(__input_value, StarletteUploadFile):\n            raise ValueError(f\"Expected UploadFile, received: {type(__input_value)}\")\n        return cast(UploadFile, __input_value)\n\n    @classmethod\n    def __get_pydantic_json_schema__(\n        cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler\n    ) -> dict[str, Any]:\n        return {\"type\": \"string\", \"contentMediaType\": \"application/octet-stream\"}\n\n    @classmethod\n    def __get_pydantic_core_schema__(\n        cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]]\n    ) -> Mapping[str, Any]:\n        from ._compat.v2 import with_info_plain_validator_function\n\n        return with_info_plain_validator_function(cls._validate)\n\n\nclass DefaultPlaceholder:","sourceCodeStart":117,"sourceCodeEnd":153,"githubUrl":"https://github.com/tiangolo/fastapi/blob/42a41db11f6882807ac3c057b942178d53b97438/fastapi/datastructures.py#L117-L153","documentation":"ValueError raised by UploadFile._validate at datastructures.py:135. UploadFile registers a Pydantic validator (__get_pydantic_core_schema__ -> with_info_plain_validator_function(cls._validate)); during request parsing it checks isinstance(__input_value, StarletteUploadFile) and raises ValueError(f'Expected UploadFile, received: {type(__input_value)}') if the value is not an UploadFile. This happens when something feeds a non-file value into a parameter typed as UploadFile.","triggerScenarios":"Calling code (often tests or internal serialization) that constructs/replays a request body and passes a plain str/bytes/dict where the schema expects an UploadFile; JSON body sent to a route declaring file: UploadFile; calling UploadFile._validate directly with a non-file; programmatic TestClient calls that bypass multipart framing.","commonSituations":"Unit tests passing a raw string instead of a file-like object to a dependency; sending application/json where multipart/form-data with a file part is required; replaying a cached request body that lost the UploadFile wrapper; mismatch between route signature (UploadFile) and client payload.","solutions":["Send the file as multipart/form-data with a proper file part, not a JSON body.","In tests, construct a real UploadFile or use httpx files=... with TestClient so the framework wraps the part.","Align the route parameter type with the actual payload (use str/bytes + Form() if it's text, UploadFile only for files).","If invoking _validate manually, pass a starlette.datastructures.UploadFile instance."],"exampleFix":"# before\nclient.post('/uploadfile/', json={'file': 'hello'})\n# after\nclient.post('/uploadfile/', files={'file': ('f.txt', b'hello', 'text/plain')})","handlingStrategy":"type-guard","validationCode":"from starlette.datastructures import UploadFile\ndef coerce_upload(value):\n    if isinstance(value, UploadFile):\n        return value\n    raise TypeError('pass a multipart file part, not JSON')","typeGuard":"from starlette.datastructures import UploadFile\nimport typing\ndef is_upload_file(v: typing.Any) -> typing.TypeGuard[UploadFile]:\n    return isinstance(v, UploadFile)","tryCatchPattern":"from fastapi.datastructures import UploadFile\ntry:\n    UploadFile._validate(value, None)\nexcept ValueError as e:\n    raise TypeError(f'wrap as UploadFile before sending: {e}') from e","preventionTips":["Send files as multipart/form-data with a file part, never JSON.","In tests use httpx/TestClient files=... so the framework wraps the part.","Match the route parameter type to the payload (UploadFile for files, Form/str for text).","Don't call UploadFile._validate directly with raw values."],"tags":["uploadfile","pydantic","validation","multipart","fastapi"],"analyzedSha":"42a41db11f6882807ac3c057b942178d53b97438","analyzedAt":"2026-08-04T19:23:32.007Z","schemaVersion":2}