{"record":{"id":"3ff3be6e08ec3d99","repo":"psf/requests","slug":"url-has-an-invalid-label","errorCode":null,"errorMessage":"URL has an invalid label.","messagePattern":"URL has an invalid label\\.","errorType":"exception","errorClass":"InvalidURL","httpStatus":null,"severity":"error","filePath":"src/requests/models.py","lineNumber":532,"sourceCode":"\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\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n","sourceCodeStart":514,"sourceCodeEnd":550,"githubUrl":"https://github.com/psf/requests/blob/8068356288978c4f54661ae6f95afe0e0831885e/src/requests/models.py#L514-L550","documentation":"Raised by PreparedRequest.prepare_url when the host contains non-ASCII characters and the IDNA encoding step (_get_idna_encoded_host) raises UnicodeError. IDNA encoding converts internationalized domain names to punycode; if a label violates IDNA rules (overlong label, invalid characters, disallowed joiners), encoding fails and requests surfaces it as InvalidURL. This guards against sending unresolvable hostnames.","triggerScenarios":"Passing a Unicode hostname with an illegal label — e.g. labels longer than 63 chars, empty labels, or characters disallowed by IDNA 2008; hostnames with zero-width joiners or other unsupported Unicode; mixed RTL/LTR scripts.","commonSituations":"User-entered internationalized domains that look valid but violate IDNA length/character rules; data-entry from locales with characters outside IDNA's allowed set; truncation that splits a label mid-codepoint.","solutions":["Pre-validate the hostname with encodings.idna.ToASCII (or idna.encode) in a try/except and reject invalid inputs before calling requests.","Shorten labels to <=63 characters and remove unsupported characters.","If the domain is genuinely valid IDNA, ensure you pass the Unicode form (not a half-encoded punycode mix) and let requests do the encoding."],"exampleFix":"// before\nrequests.get('https://exa' + 'm'*70 + 'mple.com/path')\n\n// after\nhost = 'exa' + 'm'*70 + 'mple.com'\ntry:\n    import idna\n    host = idna.encode(host).decode('ascii')\nexcept idna.IDNAError:\n    raise ValueError(f'invalid host: {host!r}')\nrequests.get(f'https://{host}/path')","handlingStrategy":"validation","validationCode":"import idna\n\ndef is_idna_valid(host: str) -> bool:\n    try:\n        idna.encode(host)\n        return True\n    except idna.IDNAError:\n        return False","typeGuard":"import idna\nfrom typing import Union\n\ndef valid_idna_host(host: str) -> Union[str, None]:\n    \"\"\"Return punycode host if valid, else None.\"\"\"\n    try:\n        return idna.encode(host).decode('ascii')\n    except idna.IDNAError:\n        return None","tryCatchPattern":"from requests.exceptions import InvalidURL\n\ntry:\n    resp = requests.get(f'https://{host}/path')\nexcept InvalidURL as e:\n    if 'invalid label' in str(e):\n        # reject or sanitize the hostname\n        ...\n    raise","preventionTips":["Validate internationalized hostnames with idna.encode before sending.","Keep DNS labels <=63 characters.","Reject hostnames with disallowed Unicode characters upstream."],"tags":["url","invalidurl","idna","unicode","dns"],"backgroundTag":null,"analyzedSha":"8068356288978c4f54661ae6f95afe0e0831885e","analyzedAt":"2026-08-11T20:11:09.238Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}