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):
async with session.get(url, timeout=10) as resp:
resp.raise_for_status()
return await resp.json()

async def main():
async with aiohttp.ClientSession() as session:
data = await asyncio.gather(*(fetch(session, url) for url in urls))

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