Search code examples
python-3.xpython-asyncioaiohttp

Why does the json() method of an aiohttp response require await?


I do not understand why resp.json() needs to be awaited. From my understanding async/await is useful when dealing with I/O. But when I call resp.json() in the example below, has the web request not already been processed with session.get() in the line above?

async with session.get('https://api.github.com/events') as resp:
    print(await resp.json())

Solution

  • But when I call resp.json() in the example below, has the web request not already been processed with session.get() in the line above?

    No, it reads only HTTP headers, to get response body you need to read the rest of the response.

    It's pretty useful since you can check HTTP headers and avoid reading the rest of the response if, let's say, server returned wrong HTTP code.

    Another example: if you expect response body to be big, you can read it by chunks to avoid RAM overusage (check note here).