{"record":{"id":"3109338761042325","repo":"psf/requests","slug":"e-args","errorCode":null,"errorMessage":"{e.args}","messagePattern":"\\{e\\.args\\}","errorType":"exception","errorClass":"InvalidURL","httpStatus":null,"severity":"error","filePath":"src/requests/models.py","lineNumber":513,"sourceCode":"            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # 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:","sourceCodeStart":495,"sourceCodeEnd":531,"githubUrl":"https://github.com/psf/requests/blob/8068356288978c4f54661ae6f95afe0e0831885e/src/requests/models.py#L495-L531","documentation":"Raised by PreparedRequest.prepare_url when the underlying url_parse raises LocationParseError (from urllib3's src/urllib3/util/url.py). The message is reconstructed from the original error's args so the caller sees the precise parse failure (e.g. which character broke parsing). This wraps a low-level parse exception in requests' own InvalidURL for a consistent exception hierarchy.","triggerScenarios":"Passing a malformed URL to requests.get/Session.request — e.g. unbalanced brackets in IPv6 ('http://[::1'), stray characters, spaces, or control characters; URLs with invalid percent-encoding; URLs constructed by string concatenation that produced garbage.","commonSituations":"Building URLs from untrusted/user input without validation; copy-paste artifacts (trailing spaces, smart quotes); templating bugs that emit 'http:///host' (triple slash) or missing protocol separators.","solutions":["Validate or sanitize the URL before passing it to requests (use urllib.parse.urlparse and check .scheme/.netloc are non-empty).","Strip whitespace and control characters from URL components: url.strip().","URL-encode path/query segments with urllib.parse.quote before assembly."],"exampleFix":"// before\nrequests.get(user_input)\n\n// after\nfrom urllib.parse import urlparse\np = urlparse(user_input.strip())\nif not p.scheme or not p.netloc:\n    raise ValueError(f'bad url: {user_input!r}')\nrequests.get(p.geturl())","handlingStrategy":"validation","validationCode":"from urllib.parse import urlparse\n\ndef is_parseable_url(url: str) -> bool:\n    try:\n        p = urlparse(url)\n        return bool(p.scheme) and bool(p.netloc)\n    except ValueError:\n        return False","typeGuard":"from urllib.parse import urlparse\n\ndef is_well_formed_url(url: str) -> bool:\n    if not isinstance(url, str) or not url.strip():\n        return False\n    p = urlparse(url.strip())\n    return bool(p.scheme in ('http', 'https')) and bool(p.netloc)","tryCatchPattern":"from requests.exceptions import InvalidURL\n\ntry:\n    resp = requests.get(url)\nexcept InvalidURL as e:\n    # log and reject the input\n    raise","preventionTips":["Validate URLs with urllib.parse.urlparse before sending.","Strip whitespace and control characters from URL inputs.","URL-encode path/query components with urllib.parse.quote."],"tags":["url","invalidurl","parsing","validation","http"],"backgroundTag":null,"analyzedSha":"8068356288978c4f54661ae6f95afe0e0831885e","analyzedAt":"2026-08-11T20:11:09.238Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}