encode/httpx · error · KeyError

{name}

Error message

{name}

What it means

Raised as `KeyError(name)` by `Cookies.__getitem__` when no cookie with that name exists in the jar (or all matching values are None). `cookies['x']` is a strict lookup; unlike `cookies.get('x')` it does not return a default, so a missing cookie propagates as a standard Python mapping error.

Source

Thrown at httpx/_models.py:1216

        if domain is not None:
            args.append(domain)
        if path is not None:
            assert domain is not None
            args.append(path)
        self.jar.clear(*args)

    def update(self, cookies: CookieTypes | None = None) -> None:  # type: ignore
        cookies = Cookies(cookies)
        for cookie in cookies.jar:
            self.jar.set_cookie(cookie)

    def __setitem__(self, name: str, value: str) -> None:
        return self.set(name, value)

    def __getitem__(self, name: str) -> str:
        value = self.get(name)
        if value is None:
            raise KeyError(name)
        return value

    def __delitem__(self, name: str) -> None:
        return self.delete(name)

    def __len__(self) -> int:
        return len(self.jar)

    def __iter__(self) -> typing.Iterator[str]:
        return (cookie.name for cookie in self.jar)

    def __bool__(self) -> bool:
        for _ in self.jar:
            return True
        return False

    def __repr__(self) -> str:
        cookies_repr = ", ".join(

View on GitHub (pinned to b5addb64f0)

Solutions

  1. Use `response.cookies.get('token')` (returns None) or `.get('token', '')` for a default.
  2. Check membership first: `if 'token' in response.cookies:`.
  3. Verify the actual cookie names with `print(list(response.cookies))`.
  4. Confirm the request URL's host/path matches the cookie scope.

Example fix

// before
token = response.cookies['token']  # KeyError if absent

// after
token = response.cookies.get('token')
if token is None:
    raise AuthError('missing token cookie')
Defensive patterns

Strategy: validation

Validate before calling

name = 'token'
if name not in response.cookies:
    raise AuthError(f'missing {name} cookie')
value = response.cookies[name]

Type guard

import httpx

def has_cookie(resp: httpx.Response, name: str) -> bool:
    return name in resp.cookies

Try / catch

try:
    value = response.cookies['token']
except KeyError:
    value = None  # or handle missing-cookie case

Prevention

When it happens

Trigger: Indexing `response.cookies['token']` or `client.cookies['token']` when the server never sent a `Set-Cookie: token=...` header, or sent it under a different name/attribute that the jar did not store under that key.

Common situations: Assuming a cookie exists before login; typos in the cookie name; cookies scoped to a different path/domain than the request; case-sensitivity mistakes.

Related errors


AI-assisted analysis of encode/httpx@b5addb64f0 (2026-08-04). Data as JSON: /data/errors/5df153b1b96b8625.json. Report an issue: GitHub.