HTTP data handling
aiohttp turns HTTP bytes into structured messages and readable body streams, then turns application values back into framed HTTP output. The same data model supports both server requests and client responses, while request and response objects keep the headers, URL, cookies, transport state, and application state that give each body its meaning.
HTTP body flow
Incoming body flow
The incoming path separates message parsing from body consumption. aiohttp/http_parser.py reads the request or response line and headers, determines how the body ends, and connects the body to the asynchronous stream in aiohttp/streams.py. The server exposes that stream through BaseRequest, while the client exposes it through ClientResponse.
The parser can use a declared length, HTTP chunk framing, or connection end to find the body boundary. It also keeps body bytes after one message available for the next message, which allows persistent connections to carry more than one exchange.
This diagram shows how wire data becomes either a server request view or a client response view.
flowchart LR
Wire[HTTP bytes] --> Message[Parsed line and headers]
Message --> Framing[Body framing]
Framing --> Stream[Async body stream]
Stream --> Server[Server request]
Stream --> Client[Client response]
Framing --> Decode[Optional content decoding]
Decode --> Stream
References: aiohttp/http_parser.py• L162-241 aiohttp/http_parser.py• L329-583 aiohttp/http_parser.py• L842-916 aiohttp/streams.py• L71-185
Outgoing body flow
The outgoing path accepts application data in several forms and gives it one payload interface. The client uses ClientRequest to choose a payload and transfer headers. The server uses Response or StreamResponse to select a body and then sends it through the HTTP stream writer.
Known-size data can use Content-Length. Data with no known size uses chunked transfer when the protocol permits it. The writer applies framing and backpressure so application code can send large or live bodies without first building one complete byte string.
flowchart LR
Value[Application value] --> Adapt[Payload or form adapter]
Adapt --> Headers[Body headers and size]
Headers --> Writer[HTTP stream writer]
Writer --> Framing[Content-Length or chunked framing]
Framing --> Wire[HTTP bytes]
References: aiohttp/client_reqrep.py• L1241-1284 aiohttp/client_reqrep.py• L1450-1523 aiohttp/web_response.py• L354-443 aiohttp/http_writer.py• L168-221
Body representations
Raw body streams
StreamReader is the common asynchronous view of an HTTP body. It supports reads by size, reads of currently available data, line iteration, and chunk iteration. It tracks end of input and read errors, and it can pause the protocol when the consumer does not keep up.
The stream is the low-level form of the body. It is best for forwarding data or handling large content incrementally. Higher-level helpers consume it and may cache the complete result for later reads.
References: aiohttp/streams.py• L71-185 aiohttp/streams.py• L217-247 aiohttp/web_request.py• L665-685 aiohttp/client_reqrep.py• L697-711
Typed body views
Server and client objects provide text and JSON views on top of the raw stream. Text uses the charset from Content-Type and falls back to UTF-8. JSON checks the expected media type by default before it decodes the body and passes it to the selected JSON loader.
These helpers read the whole body. Server requests cache the bytes for later read() calls, and client responses cache the bytes in the response object. They are therefore convenient for small bodies but are not a replacement for streaming reads.
References: aiohttp/web_request.py• L687-736 aiohttp/client_reqrep.py• L697-771
Payload adaptation
aiohttp/payload.py defines a payload as a value that can provide HTTP headers, a byte size when known, a text form, and asynchronous write behavior. The payload registry maps common values such as bytes, strings, file-like objects, streams, and asynchronous byte iterators to that interface.
Payloads can report a size for normal transfer framing or write within a caller-provided length limit. In-memory values can be reused directly, while file-backed and one-shot stream values track consumption and resource ownership. Reading an asynchronous iterable into bytes caches its chunks for later reuse; writing it directly remains a streaming operation.
The client also turns form data into a payload and copies payload headers into the request when the caller has not set them. Responses use the same model for byte bodies and for resource-backed or streamed bodies. Payloads that own resources must be closed when they are replaced or finished.
See Payloads, forms, and multipart for the detailed rules for payload types and multipart data.
References: aiohttp/payload.py• L61-120 aiohttp/payload.py• L140-337 aiohttp/payload.py• L340-419 aiohttp/payload.py• L454-721 aiohttp/payload.py• L976-1124 aiohttp/client_reqrep.py• L1241-1284 aiohttp/web_response.py• L607-635
HTTP transformations
Transfer framing
Transfer framing describes how the receiver finds the end of a body. aiohttp treats Content-Length and Transfer-Encoding: chunked as separate framing choices and rejects a message that uses both. It also handles bodies that must be empty because of the method or response status.
On output, a known body size normally becomes Content-Length. A body without a known size can become chunked on HTTP/1.1. The response status, request method, and protocol version can remove a body or force the connection to close instead.
References: aiohttp/http_parser.py• L398-511 aiohttp/http_parser.py• L621-637 aiohttp/client_reqrep.py• L1222-1239 aiohttp/web_response.py• L372-424
Content encoding
Content encoding changes the representation of body bytes without changing the application data. On input, aiohttp can decode supported response or request content as it feeds the stream, so text and JSON helpers see decoded bytes. The stream still records both decoded and compressed byte counts for size and monitoring decisions.
On output, client request compression uses deflate or gzip and requires chunked transfer because compression changes the final size. Server response compression can select an encoding from Accept-Encoding, or use an explicitly forced encoding. A body that already has Content-Encoding is not compressed again.
See Cookies, compression, and utilities for compression support and related HTTP helpers.
References: aiohttp/http_parser.py• L621-637 aiohttp/http_parser.py• L878-902 aiohttp/http_parser.py• L1131-1176 aiohttp/client_reqrep.py• L1200-1220 aiohttp/web_response.py• L182-197 aiohttp/web_response.py• L330-351
Multipart body boundaries
Multipart data is a body made of parts separated by a boundary. MultipartReader advances through nested parts without requiring the whole body in memory, and BodyPartReader exposes each part as a bounded stream with its own headers and optional decoding. Advancing to the next part finishes the previous part so the shared body stream stays aligned.
Part reads preserve encoded data across chunk boundaries before per-part decoding. This keeps base64 transfer data aligned for each decoded chunk while still allowing the part to remain a stream. Parts can expose text, JSON, form, and disposition metadata views. Large parts can be copied directly to another writer without buffering them for reuse.
Server form parsing builds on this reader. It returns text fields as strings, binary fields as bytes, and uploaded files as FileField values. The request size limit applies while parts are read, so multipart parsing remains tied to the same body safety rules as ordinary request reads.
Multipart output uses the payload model to write boundaries, part headers, and part data. A writer can calculate a total size only when its parts have known sizes and no per-part encoding changes the size. Otherwise it streams the body. Multipart form-data supplies part disposition metadata and does not allow conflicting per-part framing or encoding headers.
See Payloads, forms, and multipart for form encoding, nested parts, and multipart writing.
References: aiohttp/multipart.py• L78-240 aiohttp/multipart.py• L289-399 aiohttp/multipart.py• L514-645 aiohttp/multipart.py• L666-705 aiohttp/multipart.py• L707-939 aiohttp/multipart.py• L943-1138 aiohttp/multipart.py• L1182-1292
Request-associated state
Request metadata
BaseRequest combines the body stream with the metadata needed by a server handler. It presents headers as a case-insensitive mapping, keeps raw header pairs when exact wire data matters, and derives URL, scheme, host, remote address, method, version, and keep-alive state from the parsed message and transport.
The request is also a mutable mapping for handler state. String keys provide a flexible store, while RequestKey gives application code a typed key. Cloning creates a new request view with copied state and selected metadata changes, but it cannot occur after the body has been read.
References: aiohttp/web_request.py• L148-218 aiohttp/web_request.py• L220-279 aiohttp/web_request.py• L389-539 aiohttp/web_request.py• L612-667
Client response state
ClientResponse gives a client the status line, headers, URLs, response history, body stream, and request information that belong to one exchange. Reading the body to completion releases the connection for reuse. Explicit release or close handles a response whose body will not be read.
This lifecycle links data handling to connection pooling: an unread or failed body cannot be treated as clean input for the next exchange. Context-manager use provides the normal boundary for releasing the response and waiting for cleanup.
References: aiohttp/client_reqrep.py• L246-279 aiohttp/client_reqrep.py• L515-566 aiohttp/client_reqrep.py• L568-711 aiohttp/client_reqrep.py• L773-789
Cookie state
Cookies are request-associated state carried in headers rather than in the body. Server requests expose parsed incoming cookie values, while responses collect cookies that become Set-Cookie headers when the response starts. Client responses preserve received cookie headers so the session cookie store can process them.
The client CookieJar stores cookies by domain and path, accepts them against the response URL, and filters them for each request URL. It applies host-only, secure, domain, path, and expiry rules before it creates the outgoing cookie header. The built-in jar also bounds stored cookies by domain and in total, limits the number and size of cookies sent in one request, and uses expiry and least-recently-used eviction when it must make room. It rejects cookie values that cannot be sent safely. Relative and absolute expiry values become bounded deadlines, and non-positive Max-Age values expire a cookie at once.
The jar can persist cookies to JSON while retaining host-only scope and absolute expiry times. New persistence files use owner-only access. Loading replaces the current contents only after the saved data passes validation and sends restored cookies through the same acceptance rules. DummyCookieJar disables this processing when a session does not need cookies.
Cookie parsing and cookie policy are separate from body parsing. See Cookies, compression, and utilities for the complete cookie and utility model.
References: aiohttp/web_request.py• L617-626 aiohttp/helpers.py• L1022-1125 aiohttp/client_reqrep.py• L381-405 aiohttp/client_reqrep.py• L551-566 aiohttp/cookiejar.py• L66-139 aiohttp/cookiejar.py• L164-281 aiohttp/cookiejar.py• L389-615 aiohttp/cookiejar.py• L617-780 aiohttp/cookiejar.py• L862-922
Change checklist
When these files or sections are changed, remember to consider these:
- Keep body framing, parser EOF handling, and connection reuse aligned for
Content-Length, chunked transfer, and close-delimited bodies. - Keep payload size and header rules aligned between the payload registry, client request setup, multipart writers, and server responses.
- Preserve the distinction between compressed input size and decoded body size when changing decompression or request size limits.
- Treat
content,read(),post(), andmultipart()as consumers of one body stream. Changes to one reader can change what later readers see. - Preserve multipart transfer-decoding alignment across stream reads so base64 data is not split between independently decoded chunks.
- Preserve multipart part-draining, nested-boundary handoff, and response release behavior when changing part iteration or nested boundaries.
- When changing response cleanup, verify that full reads, explicit release, cancellation, and connection pooling still agree.
- When changing request cloning or state keys, preserve the rule that body consumption prevents safe cloning and that cloned state is independent.
- When changing payload length limits or replay behavior, keep known sizes, constrained writes, redirects, and one-shot streams consistent.
- When changing cookie acceptance, filtering, or persistence, keep domain, path, host-only, secure, expiry, sendability, storage quotas, request header limits, eviction, and file-permission rules consistent between stored and restored cookies.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
Content-Length is malformed, incomplete, or conflicts with transfer encoding | The parser raises an HTTP processing error and cannot safely continue the exchange | Validate framing headers before the body is consumed; use one framing method |
A request body exceeds client_max_size while read(), form parsing, or multipart parsing runs | aiohttp raises HTTPRequestEntityTooLarge and stops the body operation | Set a suitable per-application or per-request limit and stream large input |
| A body uses an unavailable content codec such as Brotli or Zstandard | The body stream raises a content encoding error | Install the optional codec or disable automatic decompression when raw bytes are required |
Code reads a body and then calls post() or multipart() | The later parser sees an exhausted stream and may return incomplete or empty data | Choose one body consumption path for each request |
| A multipart part is not drained before the reader advances | Boundary data can be consumed as part data and later parts become misaligned | Read the part to EOF or use its release operation before moving to another consumer |
| A multipart body has a missing or overlong boundary, or too many part headers | Multipart parsing stops before it can produce a safe part stream | Send a valid boundary and keep part headers within configured limits |
| A client response is neither read nor released | The connection stays occupied or must be closed instead of being reused | Use async with, read the body, or call release() / close() |
| Code changes a request body by direct assignment when the old payload owns resources | File handles or stream resources can remain open | Use the asynchronous body update path so the old payload is closed |
| A one-shot asynchronous payload is interrupted after its iterator advances | A retry or redirect can send only the remaining data or no data | Buffer with as_bytes() when replay is required, or provide a replayable payload |
| A cookie store reaches its domain, total, or outgoing header limit | Cookies can be evicted or omitted from the request, and a new cookie can be dropped when no safe room remains | Keep cookie state within the jar's bounds and do not rely on every stored cookie being sent |
| A cookie is restored without its host-only or expiry metadata | The cookie can be sent to subdomains or remain after its intended lifetime | Use the cookie jar persistence path and keep its metadata with the cookie value |
A very large positive Max-Age is added to the current time before it is bounded | Expiry calculation can overflow instead of producing a safe deadline | Bound the duration before time addition and cap the resulting deadline |
Key files
| File | Why to read it |
|---|---|
| aiohttp/http_parser.py | Defines the boundary between HTTP wire parsing, body framing, content decoding, and asynchronous body streams. |
| aiohttp/streams.py | Defines the common stream behavior used for incremental reads, end-of-input, errors, and backpressure. |
| aiohttp/web_request.py | Shows how server handlers consume body data and access request metadata and state. |
| aiohttp/client_reqrep.py | Shows how client requests adapt outgoing data and how client responses expose and release incoming data. |
| aiohttp/payload.py | Defines the shared body abstraction used to write bytes, text, files, streams, and JSON. |
| aiohttp/web_response.py | Shows how server response bodies become headers, framing, compression, and final output. |
| aiohttp/multipart.py | Defines streaming multipart reads and writes, including part boundaries and part-level data handling. |
| aiohttp/cookiejar.py | Defines client cookie storage, URL-based selection, expiry, bounded storage and headers, persistence, and disabled-cookie behavior. |
| aiohttp/http_writer.py | Defines the final output stage for headers, body bytes, compression, chunking, and EOF. |