{"record":{"id":"7dded4fecb39cb02","repo":"psf/requests","slug":"e","errorCode":null,"errorMessage":"{e}","messagePattern":"\\{e\\}","errorType":"exception","errorClass":"InvalidURL","httpStatus":null,"severity":"error","filePath":"src/requests/adapters.py","lineNumber":491,"sourceCode":"        :param proxies:\n            (optional) The proxies dictionary to apply to the request.\n        :param cert:\n            (optional) Any user-provided SSL certificate to be used for client\n            authentication (a.k.a., mTLS).\n        :rtype:\n            urllib3.HTTPConnectionPool\n        \"\"\"\n        assert _is_prepared(request)\n\n        proxy = select_proxy(request.url, proxies)\n        try:\n            host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n                request,\n                verify,\n                cert,\n            )\n        except ValueError as e:\n            raise InvalidURL(e, request=request)\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n        else:\n            # Only scheme should be lower case\n            conn = self.poolmanager.connection_from_host(\n                **host_params, pool_kwargs=pool_kwargs\n            )\n","sourceCodeStart":473,"sourceCodeEnd":509,"githubUrl":"https://github.com/psf/requests/blob/8068356288978c4f54661ae6f95afe0e0831885e/src/requests/adapters.py#L473-L509","documentation":"This is a re-raise of a ValueError from build_connection_pool_key_attributes as an InvalidURL, attaching the request. The underlying ValueError comes from urllib3/requests connection-key construction (e.g. an unparseable host, missing host, or bad port). Wrapping it as InvalidURL gives callers a consistent exception type for malformed URL problems during connection setup in get_connection_with_tls_context's caller path (send -> proxy branch).","triggerScenarios":"Triggered when build_connection_pool_key_attributes cannot build a valid urllib3 connection key from the request URL, such as a URL with no host, an invalid port, or an unsupported scheme. It surfaces inside the send flow at the point host_params and pool_kwargs are computed, before any network activity.","commonSituations":"Happens with programmatically-built URLs that drop the host, with international/IDN hostnames that fail encoding, with URLs containing stray characters or bad port segments, or when a redirect chain yields an invalid Location header URL.","solutions":["Validate the URL with requests.utils.urlparse / urllib.parse.urlparse and confirm .hostname and .port are sane before sending.","Sanitize or reject URLs without a host or with non-numeric ports before they reach the adapter.","If redirects are involved, inspect the response chain and reject malformed Location values.","Pin/normalize the scheme to http or https and reject anything else upstream.","Add a unit test that feeds your URL builder edge cases (empty host, bad port) to catch regressions."],"exampleFix":"# before\nrequests.get(\"http://:8080/path\")  # no host -> InvalidURL\n\n# after\nfrom urllib.parse import urlparse\nu = urlparse(\"http://example.com:8080/path\")\nif not u.hostname:\n    raise ValueError(f\"URL has no host: {u.geturl()}\")\nrequests.get(u.geturl())","handlingStrategy":"validation","validationCode":"from urllib.parse import urlparse\n\ndef assert_valid_target_url(url: str) -> str:\n    \"\"\"Reject URLs that would break connection-key construction.\"\"\"\n    p = urlparse(url)\n    if not p.hostname:\n        raise ValueError(f\"URL has no host: {url!r}\")\n    if p.scheme.lower() not in (\"http\", \"https\"):\n        raise ValueError(f\"unsupported scheme: {p.scheme}\")\n    if p.port is not None and not (0 < p.port < 65536):\n        raise ValueError(f\"invalid port: {p.port}\")\n    return url\n\nrequests.get(assert_valid_target_url(url))","typeGuard":"from urllib.parse import urlparse\n\ndef is_valid_request_url(url) -> bool:\n    if not isinstance(url, str) or not url:\n        return False\n    p = urlparse(url)\n    if not p.hostname:\n        return False\n    if p.scheme.lower() not in (\"http\", \"https\"):\n        return False\n    if p.port is not None and not (0 < p.port < 65536):\n        return False\n    return True","tryCatchPattern":"import requests.exceptions as exc\n\ntry:\n    resp = session.get(url)\nexcept exc.InvalidURL as e:\n    # log and reject the URL upstream rather than retrying blindly\n    raise ValueError(f\"refusing malformed URL {url!r}: {e}\") from e","preventionTips":["Build URLs with a single tested helper, never by string concatenation.\nReject empty-host and non-http(s) schemes before they reach requests.\nAdd unit tests for IDN, empty-host, and bad-port edge cases.\nWhen following redirects, validate each Location before requesting it."],"tags":["url","validation","invalid-url","send"],"backgroundTag":null,"analyzedSha":"8068356288978c4f54661ae6f95afe0e0831885e","analyzedAt":"2026-08-11T20:11:09.238Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}