python network_error ai_generated true

aiohttp.client_exceptions.InvalidURL: URL should be absolute

ID: python/aiohttp-invalid-url-with-scheme

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —

Root Cause

aiohttp requires fully qualified URLs including scheme and host; relative paths or strings missing http(s):// are rejected.

generic

中文

aiohttp 要求完全限定的 URL,必须包含协议和主机;相对路径或缺少 http(s):// 的字符串会被拒绝。

Workarounds

  1. 95% success
    Use urllib.parse.urljoin to build an absolute URL:
    
    from urllib.parse import urljoin
    url = urljoin('https://api.example.com', '/v1/users')
    async with session.get(url) as resp:
        ...
  2. 90% success
    Store full URLs in your config and validate at startup:
    
    assert url.startswith(('http://', 'https://')), f'bad url: {url}'

Dead Ends

Common approaches that don't work:

  1. 70% fail

    base_url only affects redirects and links; session.get('/path') still raises InvalidURL.

  2. 80% fail

    Encoding does not add the missing scheme/host; the URL remains relative.