{"record":{"id":"7ecfdb929f9f5118","repo":"aio-libs/aiohttp","slug":"invalidurl-url","errorCode":null,"errorMessage":"InvalidURL: {url}","messagePattern":"InvalidURL: (.+?)","errorType":"exception","errorClass":"InvalidURL","httpStatus":null,"severity":"error","filePath":"aiohttp/client_reqrep.py","lineNumber":843,"sourceCode":"    ):\n        if match := _CONTAINS_CONTROL_CHAR_RE.search(method):\n            raise ValueError(\n                f\"Method cannot contain non-token characters {method!r} \"\n                f\"(found at least {match.group()!r})\"\n            )\n        # URL forbids subclasses, so a simple type check is enough.\n        assert type(url) is URL, url\n        self.original_url = url\n        self.url = url.with_fragment(None) if url.raw_fragment else url\n        self.method = method.upper()\n        self.loop = loop\n        self._ssl = ssl\n\n        if loop.get_debug():\n            self._source_traceback = traceback.extract_stack(sys._getframe(1))\n\n        if not url.raw_host:\n            raise InvalidURL(url)\n        self._update_headers(headers)\n        if url.raw_user or url.raw_password:\n            self.headers[hdrs.AUTHORIZATION] = encode_basic_auth(\n                url.user or \"\", url.password or \"\"\n            )\n\n    def _reset_writer(self, _: object = None) -> None:\n        self._writer_task = None\n\n    def _get_content_length(self) -> int | None:\n        \"\"\"Extract and validate Content-Length header value.\n\n        Returns parsed Content-Length value or None if not set.\n        Raises ValueError if header exists but cannot be parsed as an integer.\n        \"\"\"\n        if hdrs.CONTENT_LENGTH not in self.headers:\n            return None\n","sourceCodeStart":825,"sourceCodeEnd":861,"githubUrl":"https://github.com/aio-libs/aiohttp/blob/d041d4d0fd48c3f0832084d33be16cf1c4835f85/aiohttp/client_reqrep.py#L825-L861","documentation":"Raised as InvalidURL by ClientRequest.__init__ when the request URL has no raw_host (e.g. a relative URL or an empty/URL without an authority). aiohttp requires an absolute URL with a host for client requests; the check 'if not url.raw_host' fails and raises InvalidURL. This is a usage error, not a network error.","triggerScenarios":"Passing a relative path like '/path' or 'path' instead of 'http://host/path'; passing an empty URL(); passing a URL with only a scheme but no host ('http:///path'). The raw_host check in ClientRequest.__init__ fails at construction.","commonSituations":"Building URLs by string concatenation and forgetting the scheme/host; reading a path from config/env and using it directly; mixing server-side relative URLs with client requests; URL parsing edge cases producing empty hosts.","solutions":["Pass an absolute URL: 'http://example.com/path'. Use aiohttp's URL or yarl.URL to build it.","If you have a base URL and a path, combine them: str(URL(base) / path.lstrip('/')).","Validate url.raw_host is truthy before constructing the request.","Check for trailing/leading issues when assembling URLs from parts."],"exampleFix":"# before\nawait session.get('/api/users')  # InvalidURL — no host\n\n# after\nfrom yarl import URL\nbase = URL('http://api.example.com')\nawait session.get(base / 'api/users')","handlingStrategy":"validation","validationCode":"from yarl import URL\n\ndef absolute_url(url) -> URL:\n    u = URL(url) if not isinstance(url, URL) else url\n    if not u.raw_host:\n        raise ValueError(f'URL must be absolute with a host: {url!r}')\n    return u","typeGuard":"from yarl import URL\ndef is_absolute_http_url(url) -> bool:\n    try:\n        u = URL(url) if not isinstance(url, URL) else url\n    except Exception:\n        return False\n    return bool(u.raw_host) and u.scheme in ('http', 'https')","tryCatchPattern":"from aiohttp import InvalidURL\n\ntry:\n    await session.get(maybe_relative)\nexcept InvalidURL as e:\n    # prepend a base URL and retry\n    await session.get(str(URL('http://api.example.com') / maybe_relative.lstrip('/')))","preventionTips":["Always construct client URLs from a known base URL using yarl.URL.","Validate url.raw_host before issuing requests.","Keep server-relative paths out of client code unless combined with a base."],"tags":["client","request","url","validation","usage"],"backgroundTag":null,"analyzedSha":"d041d4d0fd48c3f0832084d33be16cf1c4835f85","analyzedAt":"2026-08-11T20:44:15.550Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}