{"id":"e8fe13b5afb24b50","repo":"psf/requests","slug":"invalid-url-url-r-no-host-supplied","errorCode":null,"errorMessage":"Invalid URL {url!r}: No host supplied","messagePattern":"Invalid URL (.+?): No host supplied","errorType":"exception","errorClass":"InvalidURL","httpStatus":null,"severity":"error","filePath":"src/requests/models.py","lineNumber":522,"sourceCode":"        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant https://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host","sourceCodeStart":504,"sourceCodeEnd":540,"githubUrl":"https://github.com/psf/requests/blob/414f0513c33883adf6f2b46901d4f0b38a455851/src/requests/models.py#L504-L540","documentation":"An `InvalidURL` exception raised in `prepare_url` when the URL parses successfully and has a scheme, but the host component is empty. Without a host there is nothing to connect to, so the request cannot proceed. This catches malformed URLs like 'http://' or 'http:///path'.","triggerScenarios":"`requests.get('http://')`, `requests.get('http:///path')`, `requests.get('https://:8080/x')` — any URL where `parse_url` returns an empty host. Commonly produced by string formatting where the hostname variable is empty: `f'http://{host}/api'` with `host=''`.","commonSituations":"An unset environment variable or config key interpolated into a URL template (e.g. `API_HOST` empty in a container/CI environment), yielding 'http:///endpoint'; URL builders that accept optional host; accidental double slashes replacing the authority.","solutions":["Trace where the URL was built and ensure the hostname variable is non-empty — most often a missing env var or config value.","Validate config at startup: raise a clear error if the host setting is empty instead of letting it reach requests.","Print/log the exact URL being requested (it appears in the exception message via {url!r}) to spot the empty authority."],"exampleFix":"# before\nhost = os.environ.get('API_HOST', '')\nrequests.get(f'http://{host}/health')\n\n# after\nhost = os.environ['API_HOST']  # KeyError early if unset\nif not host:\n    raise RuntimeError('API_HOST is empty')\nrequests.get(f'http://{host}/health')","handlingStrategy":"validation","validationCode":"from urllib.parse import urlparse\nparsed = urlparse(url)\nif not parsed.netloc:\n    raise ValueError(f\"URL {url!r} has no host\")","typeGuard":null,"tryCatchPattern":"from requests.exceptions import InvalidURL\ntry:\n    resp = requests.get(url)\nexcept InvalidURL:\n    ...  # e.g. 'http://' or 'http:///path' — reject or re-prompt for a real host\n    raise","preventionTips":["Check urlparse(url).netloc is non-empty before making the request","Beware string concatenation bugs that produce 'http://' + '' when a host variable is empty","Catch requests.exceptions.InvalidURL (subclass of ValueError) at the call site"],"tags":["python","requests","url","invalid-url","configuration"],"analyzedSha":"414f0513c33883adf6f2b46901d4f0b38a455851","analyzedAt":"2026-07-31T19:24:57.696Z","schemaVersion":2}