{"id":"4d51d6c38b2a016b","repo":"encode/httpx","slug":"the-request-instance-has-not-been-set-on-this-resp","errorCode":null,"errorMessage":"The request instance has not been set on this response.","messagePattern":"The request instance has not been set on this response\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"httpx/_models.py","lineNumber":601,"sourceCode":"        \"\"\"\n        if not hasattr(self, \"_elapsed\"):\n            raise RuntimeError(\n                \"'.elapsed' may only be accessed after the response \"\n                \"has been read or closed.\"\n            )\n        return self._elapsed\n\n    @elapsed.setter\n    def elapsed(self, elapsed: datetime.timedelta) -> None:\n        self._elapsed = elapsed\n\n    @property\n    def request(self) -> Request:\n        \"\"\"\n        Returns the request instance associated to the current response.\n        \"\"\"\n        if self._request is None:\n            raise RuntimeError(\n                \"The request instance has not been set on this response.\"\n            )\n        return self._request\n\n    @request.setter\n    def request(self, value: Request) -> None:\n        self._request = value\n\n    @property\n    def http_version(self) -> str:\n        try:\n            http_version: bytes = self.extensions[\"http_version\"]\n        except KeyError:\n            return \"HTTP/1.1\"\n        else:\n            return http_version.decode(\"ascii\", errors=\"ignore\")\n\n    @property","sourceCodeStart":583,"sourceCodeEnd":619,"githubUrl":"https://github.com/encode/httpx/blob/b5addb64f0161ff6bfe94c124ef76f6a1fba5254/httpx/_models.py#L583-L619","documentation":"Raised by the `Response.request` property when `_request` is None. httpx links a Response to the Request that produced it at send time; if that link was never established, accessing `.request`, `.url`, or `.next_request` is undefined, so the property refuses to return a stale/empty value. This almost always means the Response was constructed by hand (tests, mocks, fixtures, or a custom transport) rather than returned by `client.request`/`client.get`.","triggerScenarios":"Calling `httpx.Response(200, content=b'...').request`, `response.url`, or any code path that reads `self.request` on a Response built via the `httpx.Response(...)` constructor without a `request=` argument. Also triggered by `raise_for_status()` on such a Response (see error 43) and by `extract_cookies` flows that dereference `response.request`.","commonSituations":"Unit tests that build a fake `httpx.Response` for a mock transport but forget to pass `request=httpx.Request('GET', 'https://example.com')`; custom `httpx.BaseTransport`/`AsyncBaseTransport` implementations that return a hand-built Response; upgrading from `requests` where manually building Response-like objects was common.","solutions":["Pass a real request when constructing: `httpx.Response(200, request=httpx.Request('GET', url))`.","In tests, use `httpx.MockTransport` or `respx` so httpx itself wires the request onto the Response.","Guard before access: `if response._request is not None:` (private but stable) or restructure so you never need `.request` on synthetic responses.","If you only need the URL, store it separately instead of relying on `response.url`, which delegates to `response.request.url`."],"exampleFix":"// before\nresp = httpx.Response(200, content=b'ok')\nprint(resp.url)  # RuntimeError\n\n// after\nreq = httpx.Request('GET', 'https://example.com/')\nresp = httpx.Response(200, content=b'ok', request=req)\nprint(resp.url)","handlingStrategy":"validation","validationCode":"def safe_request(resp: httpx.Response) -> httpx.Request | None:\n    return getattr(resp, '_request', None)","typeGuard":"import httpx\n\ndef has_request(resp: httpx.Response) -> bool:\n    return getattr(resp, '_request', None) is not None","tryCatchPattern":"try:\n    req = response.request\nexcept RuntimeError:\n    # synthetic response - synthesize a request or skip\n    req = None","preventionTips":["Always pass request= when constructing httpx.Response by hand.","Prefer httpx.MockTransport / respx over hand-built Response objects in tests.","Custom transports must set response.request = request before returning."],"tags":["response","request","mocking","runtime-error"],"analyzedSha":"b5addb64f0161ff6bfe94c124ef76f6a1fba5254","analyzedAt":"2026-08-04T19:32:56.768Z","schemaVersion":2}