Skip to main content

Async HTTP with aiohttp

Asyncio Core

aiohttp Recipes

aiohttp brings fast async HTTP clients and servers to your toolbox. Here’s how to get productive quickly.

Client example​

import aiohttp
import asyncio

async def fetch(session, url):
timeout = aiohttp.ClientTimeout(total=10)
async with session.get(url, timeout=timeout) as resp:
resp.raise_for_status()
return await resp.json()

async def main():
urls = [
'https://api.github.com/repos/python/cpython',
'https://api.github.com/repos/aio-libs/aiohttp',
]
async with aiohttp.ClientSession() as session:
data = await asyncio.gather(*(fetch(session, url) for url in urls))
print([d['full_name'] for d in data])

asyncio.run(main())
  • Reuse ClientSession for connection pooling.
  • Use timeouts and raise_for_status() to handle failures.

Server example​

from aiohttp import web

async def handle(request):
return web.json_response({'status': 'ok'})

app = web.Application()
app.router.add_get('/health', handle)
web.run_app(app)
  • Middleware and signals mirror familiar patterns from Flask/FastAPI.
  • Combine with async DB drivers (asyncpg) for full-stack async.

Next up in your learning path