{"id":"f4ff5a851445cf94","repo":"encode/httpx","slug":"invalid-type-for-value-expected-primitive-type-g","errorCode":null,"errorMessage":"Invalid type for value. Expected primitive type, got {type(value)}: {value!r}","messagePattern":"Invalid type for value\\. Expected primitive type, got (.+?): (.+?)","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"httpx/_multipart.py","lineNumber":81,"sourceCode":"    if b\";\" in content_type:\n        for section in content_type.split(b\";\"):\n            if section.strip().lower().startswith(b\"boundary=\"):\n                return section.strip()[len(b\"boundary=\") :].strip(b'\"')\n    return None\n\n\nclass DataField:\n    \"\"\"\n    A single form field item, within a multipart form field.\n    \"\"\"\n\n    def __init__(self, name: str, value: str | bytes | int | float | None) -> None:\n        if not isinstance(name, str):\n            raise TypeError(\n                f\"Invalid type for name. Expected str, got {type(name)}: {name!r}\"\n            )\n        if value is not None and not isinstance(value, (str, bytes, int, float)):\n            raise TypeError(\n                \"Invalid type for value. Expected primitive type,\"\n                f\" got {type(value)}: {value!r}\"\n            )\n        self.name = name\n        self.value: str | bytes = (\n            value if isinstance(value, bytes) else primitive_value_to_str(value)\n        )\n\n    def render_headers(self) -> bytes:\n        if not hasattr(self, \"_headers\"):\n            name = _format_form_param(\"name\", self.name)\n            self._headers = b\"\".join(\n                [b\"Content-Disposition: form-data; \", name, b\"\\r\\n\\r\\n\"]\n            )\n\n        return self._headers\n\n    def render_data(self) -> bytes:","sourceCodeStart":63,"sourceCodeEnd":99,"githubUrl":"https://github.com/encode/httpx/blob/b5addb64f0161ff6bfe94c124ef76f6a1fba5254/httpx/_multipart.py#L63-L99","documentation":"Raised as `TypeError` by `DataField.__init__` when a multipart field `value` is not one of the allowed primitive types (`str`, `bytes`, `int`, `float`, or `None`). Multipart form values must serialize to bytes; arbitrary objects (lists, dicts, custom classes) cannot be sent as plain form fields and are rejected.","triggerScenarios":"Passing `data={'opt': ['a','b']}` or `data={'obj': some_object}` to `client.post(url, data=...)`; using a dict-of-dicts where each value is structured rather than scalar.","commonSituations":"Confusing form fields with JSON bodies — passing nested data to `data=` instead of `json=`; forgetting to `json.dumps` a list before putting it in a form field; serializing ORM objects naively.","solutions":["Send structured data as JSON: `client.post(url, json=payload)` instead of `data=payload`.","If the API expects a stringified field, serialize first: `data={'opts': ','.join(opts)}` or `json.dumps(value)`.","Flatten nested structures into multiple `key[]`-style field names if the server expects repeated form fields.","Add a pre-flight type check on each value."],"exampleFix":"// before\nclient.post(url, data={'filters': {'a': 1}})  # TypeError\n\n// after\nclient.post(url, json={'filters': {'a': 1}})","handlingStrategy":"validation","validationCode":"ALLOWED = (str, bytes, int, float, type(None))\ndef validate_form_values(data: dict) -> None:\n    bad = {k: type(v).__name__ for k, v in data.items()\n           if not isinstance(v, ALLOWED)}\n    if bad:\n        raise TypeError(f'non-primitive form values: {bad}')","typeGuard":"def form_values_are_primitive(data: dict) -> bool:\n    return all(\n        v is None or isinstance(v, (str, bytes, int, float))\n        for v in data.values()\n    )","tryCatchPattern":"try:\n    client.post(url, data=payload)\nexcept TypeError:\n    # structured payload - send as JSON instead\n    client.post(url, json=payload)","preventionTips":["Send nested/structured data via json=, not data=.","Serialize lists/dicts to strings explicitly when the API truly wants a form field.","Validate each value type before building the multipart payload."],"tags":["multipart","type-error","form-data","serialization","validation"],"analyzedSha":"b5addb64f0161ff6bfe94c124ef76f6a1fba5254","analyzedAt":"2026-08-04T19:32:56.768Z","schemaVersion":2}