Learn aiohttp

Asynchronous HTTP client and server for asyncio

14 lessons · 3 hours · 4 levels · covers aiohttp 3.14

aiohttp is an asyncio-based HTTP library that provides both a high-performance client and a web server framework, with first-class WebSocket support. It is used for crawlers and API clients that make thousands of concurrent requests, and for lightweight async web services, proxies and real-time apps. Learning it means learning to do HTTP the asyncio way, with explicit sessions, connectors and lifecycles.

Before you start

aiohttp builds on these; the tree links to the exact lessons you need.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics4 lessons · 40 min in total
2. PracticalUse it productively at work, with the usual idioms8 lessons · 1 hour in total
3. AdvancedThe less common features, performance and trade-offs11 lessons · 2 hours in total
4. ExpertInternals and the edge cases experts know14 lessons · 3 hours in total

The aiohttp tree

aiohttpClientSession and your first requestClientSession andyour first requestReading responses and checking statusReading responsesand checking statusMany requests concurrentlyMany requestsconcurrentlyYour first aiohttp web serverYour first aiohttp webserverClient timeouts and exceptionsClient timeouts andexceptionsHandling request data on the serverHandling requestdata on the serverMiddlewaresMiddlewaresTesting aiohttp clients and serversTesting aiohttpclients and serversasync and await with asyncioasync and await withasyncioDecoratorsDecoratorsExceptions in depthExceptions in depthTesting with pytest and unittestTesting with pytestand unittestAdvanced generators and itertoolsAdvanced generatorsand itertoolsThreads, processes and concurrent.futuresThreads, processesand concurrent.fut…
Essentials and Practical shown (8 of 14 lessons); the full list is below. Click a lesson to read it.

All 14 lessons, in order

Client basics

  1. ClientSession and your first request · Essentials · 9 min

    Create an aiohttp.ClientSession inside async code and make GET and POST requests with async with.

  2. Reading responses and checking status · Essentials · 9 min

    Read status, headers and bodies from ClientResponse, and raise on error statuses with raise_for_status.

  3. Many requests concurrently · Essentials · 11 min

    Fetch many URLs concurrently with asyncio.gather or TaskGroup over one session, bounding concurrency with a semaphore.

Web server basics

  1. Your first aiohttp web server · Essentials · 11 min

    Build a web.Application with routes and handlers that return web.Response or web.json_response, and run it.

  2. Handling request data on the server · Practical · 11 min

    Read query parameters, JSON, forms and headers from web.Request, validate them, and return proper error responses.

Client in depth

  1. Client timeouts and exceptions · Practical · 11 min

    Configure ClientTimeout (total, connect, sock_read) and handle the ClientError hierarchy and asyncio timeouts.

  2. Connectors, pooling and DNS · Advanced · 11 min

    Tune TCPConnector limits, per-host limits, DNS caching, keep-alive and SSL to control how the client uses connections.

Server in depth

  1. Middlewares · Practical · 10 min

    Wrap every request with middleware coroutines for logging, error handling, auth and timing.

  2. Testing aiohttp clients and servers · Practical · 11 min

    Test aiohttp apps in-process with TestClient and TestServer or the pytest-aiohttp fixtures, and fake servers for client code.

  3. WebSockets: client and server · Advanced · 13 min

    Serve WebSockets with web.WebSocketResponse and connect to them with session.ws_connect, handling messages and closes.

  4. App state, startup and cleanup · Advanced · 11 min

    Manage shared resources with typed AppKey state and cleanup_ctx, on_startup and on_shutdown signals.

Production and internals

  1. Client tracing and observability · Expert · 11 min

    Hook into each phase of client requests with TraceConfig to measure DNS, connection and request timing.

  2. Deploying aiohttp servers · Expert · 12 min

    Run aiohttp in production with AppRunner and sites, Gunicorn workers, a reverse proxy, and graceful shutdown.

  3. Performance and internals · Expert · 12 min

    Understand aiohttp's C-accelerated parser, multidict and yarl, how blocking code hurts, and how to profile async services.