API Reference

aiohttp

Async HTTP client and server framework for Python built on asyncio with sessions, websockets, and middleware.

Official Documentation ↗
CompatibilityThis documentation covers version v3. Check the official docs for the latest API surface.

Installation

pippip install aiohttp

Methods

Async HTTP client and server framework for Python built on asyncio with sessions, websockets, and middleware.

Overview

aiohttp provides both sides of HTTP for asyncio: a client with connection-pooling sessions, and a server with routes and middleware. Client code reads as nested async with blocks, and the response body is awaited exactly once into json or text.

The library also speaks WebSockets on both ends, supports multipart uploads, and integrates with the standard logging ecosystem. It is the transport layer under many async Python stacks and pairs naturally with asyncpg or redis.asyncio for full async services.

Core Methods

The most frequently used entry points, with signatures and runnable examples:

  • ClientSession — Connection-pooling context manager for all client requests; create one per service, not per request.
  • session.get / session.post — Executes requests sharing the session pool; json serializes the body and params appends the query string.
  • ClientResponse helpers — Response object exposing status, an ok shorthand, exception raising, and body readers.
  • web.Application — Server side: builds an async application with routes whose handlers return web.Response objects.

Usage Notes

  • Allocate one ClientSession per external service and inject it; per-call sessions defeat pooling entirely.
  • Always pass a ClientTimeout with a total budget so slow upstreams cannot pin coroutines.
  • Use raise_for_status or explicit status checks before parsing bodies; JSON error pages parse successfully.

Common Pitfalls

  • Reading the body twice raises; capture the awaited value once per response.
  • The default timeout is effectively none for total time; add one before production.
  • Leaving sessions open at shutdown produces “Unclosed client session” warnings and leaked connections.

FAQ

Why is creating a session per request slow?
Each ClientSession owns its own connector and TCP pool. Creating one per request pays connection setup, TLS handshakes, and cleanup every time, and often trips file-descriptor limits. Build one session at startup and share it.
How do I set a total timeout?
Pass aiohttp.ClientTimeout(total=10) to the session constructor (or per request). The default has no total limit, only a 5-minute read timeout, so a stalled server can hang a coroutine indefinitely without it.
How do I close a session in a long-lived app?
Create the session in an async context at startup or store it and register cleanup: await session.close() in an Application shutdown hook or the finally of your main coroutine.