Skip to content

What it is

aiohttp is an asynchronous HTTP client/server framework for Python, built on top of asyncio for high-performance networking.

aiohttp allows asynchronous HTTP requests and building async web servers using Python’s asyncio. It supports request handling, middleware, routing, and websockets.

Installation

pip install aiohttp

Getting started

The smallest useful thing you can do with it, and what each part means.

Simple async GET request
import aiohttp
import asyncio

async def fetch():
    async with aiohttp.ClientSession() as session:
        async with session.get('https://httpbin.org/get') as resp:
            print(await resp.text())

asyncio.run(fetch())
Performs an async GET request and prints the response body.

Advanced usage

Where the library earns its place over a simpler alternative.

Creating an async web server
from aiohttp import web

async def hello(request):
    return web.Response(text='Hello, aiohttp!')

app = web.Application()
app.add_routes([web.get('/', hello)])
web.run_app(app)
Starts a basic async web server using aiohttp.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

aiohttp.ClientError
Handle network exceptions when making HTTP requests asynchronously.

Best practices

  • Use `async with` for client sessions to ensure proper cleanup.
  • Avoid blocking code in async functions; use asyncio-compatible libraries.
  • Leverage middlewares for authentication and logging.

Background

Why it exists, and what it was reacting to.

aiohttp was created to enable async HTTP requests and web servers in Python. It allows handling many connections concurrently, making it suitable for real-time web applications and APIs.