aio-libs/aiohttp · error · RuntimeError

Cannot compute fallback encoding of a not yet read body

Error message

Cannot compute fallback encoding of a not yet read body

What it means

Raised as RuntimeError in ClientResponse.get_encoding() when charset fallback logic needs to inspect the body (via _resolve_charset) but self._body is still None. get_encoding() normally reads charset from Content-Type or defaults to utf-8 for JSON; the body-based fallback only works after the body has been read into memory.

Source

Thrown at aiohttp/client_reqrep.py:730

    def get_encoding(self) -> str:
        ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower()
        mimetype = parse_mimetype(ctype)

        encoding = mimetype.parameters.get("charset")
        if encoding:
            with contextlib.suppress(LookupError, ValueError):
                return codecs.lookup(encoding).name

        if mimetype.type == "application" and (
            mimetype.subtype == "json" or mimetype.subtype == "rdap"
        ):
            # RFC 7159 states that the default encoding is UTF-8.
            # RFC 7483 defines application/rdap+json
            return "utf-8"

        if self._body is None:
            raise RuntimeError(
                "Cannot compute fallback encoding of a not yet read body"
            )

        return self._resolve_charset(self, self._body)

    async def text(self, encoding: str | None = None, errors: str = "strict") -> str:
        """Read response payload and decode."""
        await self.read()

        if encoding is None:
            encoding = self.get_encoding()

        return self._body.decode(encoding, errors=errors)  # type: ignore[union-attr]

    async def json(
        self,
        *,
        encoding: str | None = None,

View on GitHub (pinned to c0ef574e29)

Solutions

  1. Call `await response.read()` before calling `response.get_encoding()`.
  2. Prefer response.text() / response.json() which handle reading + encoding internally.
  3. If charset is known, pass it explicitly to text(encoding=...) to bypass auto-detection.

Example fix

# before
enc = response.get_encoding()      # body not yet read
body = await response.read()
# after
body = await response.read()
enc = response.get_encoding()
Defensive patterns

Strategy: validation

Validate before calling

body = await response.read()
encoding = response.get_encoding()  # safe now

Prevention

When it happens

Trigger: Fires at line 729-732 when get_encoding() is called directly before read(). Note text() and json() both call await self.read() before get_encoding(), so this only triggers when a user calls get_encoding() prematurely, or when a custom _resolve_charset callback path is invoked on an unread response.

Common situations: Calling response.get_encoding() manually before response.read(); custom subclasses that invoke charset detection early; misordered helper code in tests or middleware.

Related errors


AI-assisted analysis of aio-libs/aiohttp@c0ef574e29 (2026-08-04). Data as JSON: /data/errors/efe0c08e8859dd4a.json. Report an issue: GitHub.