{"id":"e5a4fa7fa26ed897","repo":"encode/httpx","slug":"key","errorCode":null,"errorMessage":"{key}","messagePattern":"\\{key\\}","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"warning","filePath":"httpx/_models.py","lineNumber":302,"sourceCode":"    def __getitem__(self, key: str) -> str:\n        \"\"\"\n        Return a single header value.\n\n        If there are multiple headers with the same key, then we concatenate\n        them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2\n        \"\"\"\n        normalized_key = key.lower().encode(self.encoding)\n\n        items = [\n            header_value.decode(self.encoding)\n            for _, header_key, header_value in self._list\n            if header_key == normalized_key\n        ]\n\n        if items:\n            return \", \".join(items)\n\n        raise KeyError(key)\n\n    def __setitem__(self, key: str, value: str) -> None:\n        \"\"\"\n        Set the header `key` to `value`, removing any duplicate entries.\n        Retains insertion order.\n        \"\"\"\n        set_key = key.encode(self._encoding or \"utf-8\")\n        set_value = value.encode(self._encoding or \"utf-8\")\n        lookup_key = set_key.lower()\n\n        found_indexes = [\n            idx\n            for idx, (_, item_key, _) in enumerate(self._list)\n            if item_key == lookup_key\n        ]\n\n        for idx in reversed(found_indexes[1:]):\n            del self._list[idx]","sourceCodeStart":284,"sourceCodeEnd":320,"githubUrl":"https://github.com/encode/httpx/blob/b5addb64f0161ff6bfe94c124ef76f6a1fba5254/httpx/_models.py#L284-L320","documentation":"KeyError raised by Headers.__getitem__ when the requested header key does not exist in the (case-insensitive) header multimap. Unlike dict.get, indexing with [] is strict. httpx lowercases and encodes the key for lookup; if no matching header is present it raises KeyError(key).","triggerScenarios":"response.headers['Content-Type'] when the response has no Content-Type header; request.headers['Authorization'] on a Request built without it; misspelled header name; assuming a header exists when the server omitted it.","commonSituations":"Reading optional headers without checking presence; typos (resp.headers['ContentType']); servers that conditionally omit headers (e.g. no Content-Length on chunked); HEAD requests with no body where Content-Type may be absent.","solutions":["Use .get(): response.headers.get('Content-Type') (returns None) or .get('Content-Type', default).","Use `in` first: if 'Authorization' in request.headers.","Use get_list() if the header may appear multiple times.","Validate header presence before logic that depends on it."],"exampleFix":"// before\nctype = response.headers['Content-Type']  # KeyError if absent\n// after\nctype = response.headers.get('Content-Type', 'application/octet-stream')","handlingStrategy":"validation","validationCode":"# Use .get() with a default instead of indexing\nctype = response.headers.get('Content-Type', 'application/octet-stream')\n# Or check presence first\nhas_ctype = 'Content-Type' in response.headers","typeGuard":null,"tryCatchPattern":"try:\n    ctype = response.headers['Content-Type']\nexcept KeyError:\n    ctype = 'application/octet-stream'","preventionTips":["Default to headers.get(key, default) for optional headers.","Check `key in headers` for conditional logic.","Use get_list() for headers that may repeat.","Do not assume presence of Content-Type/Content-Length on all responses."],"tags":["headers","key-access","validation"],"analyzedSha":"b5addb64f0161ff6bfe94c124ef76f6a1fba5254","analyzedAt":"2026-08-04T19:32:56.768Z","schemaVersion":2}