{"id":"d3f3bd3bc5a56115","repo":"aio-libs/aiohttp","slug":"attempt-to-decode-json-with-unexpected-mimetype","errorCode":null,"errorMessage":"Attempt to decode JSON with unexpected mimetype: %s","messagePattern":"Attempt to decode JSON with unexpected mimetype: (.+?)","errorType":"exception","errorClass":"ContentTypeError","httpStatus":null,"severity":"warning","filePath":"aiohttp/client_reqrep.py","lineNumber":757,"sourceCode":"\n        if encoding is None:\n            encoding = self.get_encoding()\n\n        return self._body.decode(encoding, errors=errors)  # type: ignore[union-attr]\n\n    async def json(\n        self,\n        *,\n        encoding: str | None = None,\n        loads: JSONDecoder = DEFAULT_JSON_DECODER,\n        content_type: str | None = \"application/json\",\n    ) -> Any:\n        \"\"\"Read and decodes JSON response.\"\"\"\n        await self.read()\n\n        if content_type:\n            if not is_expected_content_type(self.content_type, content_type):\n                raise ContentTypeError(\n                    self.request_info,\n                    self.history,\n                    status=self.status,\n                    message=(\n                        \"Attempt to decode JSON with \"\n                        \"unexpected mimetype: %s\" % self.content_type\n                    ),\n                    headers=self.headers,\n                )\n\n        if encoding is None:\n            encoding = self.get_encoding()\n\n        return loads(self._body.decode(encoding))  # type: ignore[union-attr]\n\n    async def __aenter__(self) -> \"ClientResponse\":\n        self._in_context = True\n        return self","sourceCodeStart":739,"sourceCodeEnd":775,"githubUrl":"https://github.com/aio-libs/aiohttp/blob/c0ef574e29109210e96e652771ae4e7b88615fa4/aiohttp/client_reqrep.py#L739-L775","documentation":"Raised as ContentTypeError (a ClientResponseError subclass) in ClientResponse.json() when content_type checking is enabled (the default) and the response's Content-Type header does not match the expected type. By default json() expects 'application/json'; this guard prevents silently parsing HTML error pages or text bodies as JSON.","triggerScenarios":"Fires at line 755-766 when content_type is truthy (default 'application/json') and is_expected_content_type() returns False. Common when a server returns text/html for an error (404/500), text/plain, or a vendor type like application/vnd.api+json not covered by the matcher.","commonSituations":"API returns 200 with text/html (e.g. a login page behind a redirect); reverse proxy returns an error page; vendor JSON content types; server sets charset in a way that defeats matching in older aiohttp.","solutions":["Inspect resp.status and resp.headers['Content-Type'] before calling .json().","Pass content_type=None to disable the check when you know the body is JSON regardless of type: await resp.json(content_type=None).","Pass the actual expected content type, e.g. content_type='application/vnd.api+json'.","Fix the server to return a correct JSON Content-Type."],"exampleFix":"# before\ndata = await resp.json()  # raises if server sent text/html\n# after (opt out of the check)\ndata = await resp.json(content_type=None)\n# or be specific\ndata = await resp.json(content_type='application/vnd.api+json')","handlingStrategy":"try-catch","validationCode":"ct = resp.headers.get('Content-Type', '')\nif 'json' not in ct.lower():\n    # log / handle unexpected content type before parsing\n    text = await resp.text()\nelse:\n    data = await resp.json()","typeGuard":null,"tryCatchPattern":"from aiohttp import ContentTypeError\ntry:\n    data = await resp.json()\nexcept ContentTypeError:\n    # server returned non-JSON (often HTML error page)\n    text = await resp.text()\n    raise MyApiError(f'unexpected body: {text[:200]}')","preventionTips":["Check resp.status and Content-Type before parsing.","Pass content_type=None if you intentionally accept any type.","Log response body snippets on ContentTypeError for diagnosis."],"tags":["json","content-type","response-handling","http-client"],"analyzedSha":"c0ef574e29109210e96e652771ae4e7b88615fa4","analyzedAt":"2026-08-04T19:51:05.467Z","schemaVersion":2}