Payloads, forms, and multipart bodies
Payload handling is the bridge between application values and the bytes sent or received in an HTTP body. It selects a body form, carries the related media and size rules, and supports both streamed transfer and conversion back to text, fields, JSON, or files.
Payload adaptation
The payload system gives different Python values one common body contract. A payload describes the bytes for a value, its body headers, its known size, and how it writes or closes. The request path uses this contract to choose a fixed-length or streamed transfer and to pass the payload headers to the HTTP request. aiohttp/payload.py• L61-137, aiohttp/client_reqrep.py• L1241-1284
The adaptation keeps replayable values distinct from one-shot sources. Bytes and encoded text can be sent again. A file-like value can be sent again when its position can be restored. An async iterable streams its chunks and needs caching before it can be reused. Multipart readers are also adapted as streaming values. Their payload adapter refuses byte buffering and consumes the part only through its write path. aiohttp/payload.py• L140-337, aiohttp/payload.py• L340-453, aiohttp/payload.py• L454-721, aiohttp/payload.py• L976-1124, aiohttp/multipart.py• L666-705
In-memory byte streams expose their remaining size when the payload is created. The size describes the bytes from the current position and supports a known-length request without changing the stream's application value. aiohttp/payload.py• L840-857
| Application value | Body boundary | Main effect |
|---|---|---|
| Bytes-like value | Raw bytes | Known size and reusable content |
| Text value | Encoded bytes | Charset becomes part of the content type |
| JSON value | JSON text encoded as bytes | application/json body |
| File-like value | Streamed bytes | Filename and media type can describe the file |
| Async byte iterable | Streamed chunks | Size may be unknown and the stream may be one-shot |
| Existing payload | Existing body contract | Headers and write rules are kept |
| Multipart reader part | Incoming stream | Part data is forwarded without full buffering |
The registry is extensible. A new application type can receive an adapter without changing request construction. Adapter order lets a specific type keep its special stream behavior instead of being handled by a broad adapter. aiohttp/payload.py• L61-137, aiohttp/payload.py• L1108-1124
References: aiohttp/payload.py• L61-137 aiohttp/payload.py• L140-231 aiohttp/payload.py• L340-453 aiohttp/payload.py• L976-1124 aiohttp/multipart.py• L666-705
Form body selection
FormData is an application-level collection of named fields. It delays body creation until send time. This keeps field data separate from the wire format and permits later sends to build a fresh body. A file, bytes-like value, filename, or explicit content type selects multipart form data. Plain text fields use application/x-www-form-urlencoded unless multipart mode is requested. aiohttp/formdata.py• L17-43, aiohttp/formdata.py• L49-81, aiohttp/formdata.py• L162-166
The two form modes serve different body shapes. URL encoding creates an ordered name/value byte sequence. Multipart encoding turns each field into a part with its own headers and content. Repeated names remain separate entries in both models. aiohttp/formdata.py• L107-125, aiohttp/formdata.py• L127-160
References: aiohttp/formdata.py• L17-43 aiohttp/formdata.py• L49-81 aiohttp/formdata.py• L107-166
FormData construction
Form construction records field names, values, and optional part metadata before serialization. When the request needs bytes, FormData asks the payload registry to adapt each value and gives the resulting parts to a multipart writer. This allows text, bytes, and file values to use one field interface while retaining different body headers. aiohttp/formdata.py• L49-81, aiohttp/formdata.py• L127-160
Field names, filenames, and content types cross into HTTP headers. FormData checks these values and applies the required parameter quoting so application text cannot change the structure of the generated part headers. aiohttp/formdata.py• L60-79, aiohttp/formdata.py• L147-155
References: aiohttp/formdata.py• L49-81 aiohttp/formdata.py• L127-160
Multipart body writing
MultipartWriter assembles ordered payload parts into a multipart body. It declares a media type and boundary, writes each part's headers and content, and ends with a closing boundary. A part can contain another multipart writer, which supports nested body structures. aiohttp/multipart.py• L943-1051, aiohttp/multipart.py• L1182-1210
The writer validates the boundary before it reaches the HTTP body. It accepts ASCII boundaries within the protocol length limit and quotes boundary values when the media type requires it. Form-data parts also require a field disposition, while other multipart parts may use supported compression or transfer encoding. aiohttp/multipart.py• L950-1030, aiohttp/multipart.py• L1051-1087
The writer keeps part content separate from transformations declared by part headers. It can report a total size only when every part has a known size and no transformation changes the wire length. Compression and transfer encoding are applied while the part streams. aiohttp/multipart.py• L1043-1087, aiohttp/multipart.py• L1119-1138, aiohttp/multipart.py• L1182-1209
The writer supports two body boundaries. write() streams framed bytes to the HTTP writer. The async as_bytes() path materializes the full multipart body and asks each part for bytes. A streaming multipart reader part cannot use that materialized path because its payload is one-shot. aiohttp/multipart.py• L666-705, aiohttp/multipart.py• L1155-1180, aiohttp/multipart.py• L1182-1210
The multipart writer turns adapted values into framed HTTP body bytes through this sequence:
flowchart LR
A[Application value] --> B[Payload adapter]
B --> C[Multipart part]
C --> D[Part headers and boundary]
D --> E[Optional compression or transfer encoding]
E --> F[HTTP body bytes]
For a client request, the request layer turns the application body into a payload or a form body. It uses the known size when available. Otherwise it uses streamed transfer. The request writer then asks the payload to write the body. aiohttp/client_reqrep.py• L1110-1118, aiohttp/client_reqrep.py• L1241-1284, aiohttp/client_reqrep.py• L1445-1493
References: aiohttp/multipart.py• L943-1087 aiohttp/multipart.py• L1119-1145 aiohttp/multipart.py• L1155-1210 aiohttp/multipart.py• L1211-1292 aiohttp/client_reqrep.py• L1241-1284
Multipart body reading
MultipartReader presents an incoming multipart body as an asynchronous sequence of parts. It reads the boundary and part headers as needed. It returns a BodyPartReader for normal content or another multipart reader for nested content. The reader advances by boundary and does not need to load the full body into memory. aiohttp/multipart.py• L289-396, aiohttp/multipart.py• L707-939
Each BodyPartReader provides raw byte reads and type-aware views. read() and read_chunk() keep the part as bytes until decoding is requested. text(), json(), and form() then convert the decoded bytes using the declared or default charset. Transfer decoding applies when requested. Content decoding applies to non-form-data parts. A part with an explicit zero Content-Length is treated as a known-length empty part rather than as a part whose boundary must be found by streaming. aiohttp/multipart.py• L289-399, aiohttp/multipart.py• L521-645
Content-Disposition metadata connects a part to an application field or file. The reader accepts standard, extended, and split parameter forms for names and filenames. Malformed or unsafe parameter values do not become trusted field names or paths. aiohttp/multipart.py• L78-239, aiohttp/multipart.py• L647-663
Part consumption controls the enclosing stream. When the caller asks for the next part, the reader releases unread data from the prior part. This lets a caller skip unwanted parts while preserving boundary alignment. aiohttp/multipart.py• L777-819, aiohttp/multipart.py• L931-937
The reader also treats framing and size as input limits. It checks boundary length, header count and line size, content length, required line endings, decompression size, and the configured client size while it reads or decodes. aiohttp/multipart.py• L301-329, aiohttp/multipart.py• L346-399, aiohttp/multipart.py• L870-929
Multipart response reading also owns connection release. MultipartReader.from_response() binds a reader to the response, and consuming all parts or releasing the wrapper lets the connection move on safely. aiohttp/multipart.py• L242-287, aiohttp/multipart.py• L759-819
References: aiohttp/multipart.py• L78-239 aiohttp/multipart.py• L242-399 aiohttp/multipart.py• L521-663 aiohttp/multipart.py• L707-939
Application values and HTTP body bytes
The data path keeps three forms distinct: an application value such as text or a file, a payload that describes how to turn it into bytes, and the byte stream that crosses the connection. Headers describe the body at the HTTP boundary. They do not change the source application value. aiohttp/payload.py• L140-216, aiohttp/client_reqrep.py• L1270-1284
On the server side, Request.post() turns supported form bytes back into application values. URL-encoded data becomes ordered name/value pairs. Multipart text becomes decoded strings. Multipart files become FileField values backed by temporary storage. Other multipart parts remain streaming data and are available through Request.multipart(). aiohttp/web_request.py• L738-867
The two directions across the application and HTTP boundary are:
flowchart LR
A[Application values] --> B[FormData or payload]
B --> C[Headers and body bytes]
C --> D[Multipart reader or body reader]
D --> E[Text, fields, JSON, files, or streams]
References: aiohttp/web_request.py• L738-867 aiohttp/payload.py• L140-216 aiohttp/client_reqrep.py• L1241-1284
Body lifecycle
A body can be reusable, seekable, cached, or consumed. This state matters when a request is retried or redirected because the HTTP layer may need to send the same logical body again. Resource-backed payloads also need close handling. Replacing a request body closes the old payload before it installs the new one. aiohttp/payload.py• L219-231, aiohttp/payload.py• L327-337, aiohttp/client_reqrep.py• L1303-1363
Streaming suits large or incremental data. Buffering suits data that must be read as a complete and repeatable byte value. An unseekable file or an uncached async iterable cannot be rebuilt after partial consumption. A multipart reader part follows the same one-shot rule. Its payload marks itself consumed before streaming so an interrupted write is not offered for retry or redirect. aiohttp/payload.py• L454-532, aiohttp/payload.py• L1032-1073, aiohttp/multipart.py• L666-705
Multipart writers report the consumed state of their parts. Closing the writer closes resource-backed parts that are still open. This keeps cleanup separate from the act of framing the body. aiohttp/multipart.py• L943-994, aiohttp/multipart.py• L1211-1235
References: aiohttp/payload.py• L219-231 aiohttp/payload.py• L327-337 aiohttp/payload.py• L454-532 aiohttp/payload.py• L1032-1105 aiohttp/multipart.py• L666-705 aiohttp/multipart.py• L943-994 aiohttp/multipart.py• L1211-1235 aiohttp/client_reqrep.py• L1303-1363
Related HTTP data handling
Payload and multipart handling is one part of the wider HTTP data path. For the surrounding request, response, header, and stream model, see HTTP data handling. For related cookie, compression, and utility behavior, see Cookies, compression, and utilities.
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the payload registry order aligned with specialized payloads such as multipart body parts. A broad adapter can otherwise capture a value before the adapter that preserves its streaming behavior.
- Keep payload size rules aligned with request transfer selection. An incorrect size can silently produce a wrong
Content-Lengthor the wrong transfer mode. - Keep
FormDatafield metadata aligned with multipartContent-Dispositionrules. Changes to quoting or filenames affect generated bytes and server-side field names. - Keep multipart boundary validation aligned between the media type and the body framing. A boundary that is valid in one place but not the other can make a body unreadable.
- Keep multipart writer transformations paired with reader decoding. A supported compression or transfer encoding needs matching wire headers and a matching decode path.
- Keep multipart limits aligned between the reader and
Request.post(). A part can pass boundary parsing and still exceed the application request limit while it is decoded or stored. - Keep body replacement tied to payload close behavior. Replacing a resource-backed body without closing the old payload can leak file handles or leave a stream in use.
- Keep multipart reader payloads one-shot. Forwarding one through a writer consumes the source. Materializing it with
as_bytes()is not a safe alternative.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A body value has no registered payload adapter and is not a valid form field collection | Request body construction fails instead of producing ambiguous bytes | Register an adapter or pass a supported payload or form value |
| A URL-encoded form contains a non-string value | Form serialization raises a type error | Convert the value to application text before building the form |
| A multipart boundary is missing, non-ASCII, too long, or malformed | Multipart reading or writing stops with a value error | Preserve a valid ASCII boundary in the media type and body |
| A multipart part has malformed length or boundary framing | The reader rejects the part and cannot safely continue | Treat framing errors as bad input and do not use the partial part |
| A streamed file, async iterable, or multipart reader part is sent again without rewind or caching | The second body is empty or incomplete, or materialization fails for a reader part | Rewind seekable sources or cache data before reuse |
| A decoded part exceeds the configured request or decompression limit | Reading fails with the configured size error | Set limits for the expected upload size and process parts incrementally |
| A multipart part uses an unknown content or transfer encoding | Writing or decoding raises a runtime error | Use the supported encoding set or leave the body unencoded |
| A multipart field has malformed content-disposition parameters | The field name or filename is unavailable instead of being treated as trusted metadata | Send valid disposition parameters and handle missing metadata |
Key files
| File | Why to read it |
|---|---|
| aiohttp/payload.py | Defines the common body contract and adapts application values into writable payloads. |
| aiohttp/formdata.py | Shows how named fields choose URL encoding or multipart form data. |
| aiohttp/multipart.py | Defines multipart part reading, nested readers, multipart writing, wire transformations, metadata parsing, and one-shot part forwarding. |
| aiohttp/client_reqrep.py | Connects application body input to payload headers, size selection, transfer mode, and network writes. |
| aiohttp/web_request.py | Converts incoming URL-encoded and multipart bodies into server-side fields and files. |
docs/multipart.rst | Gives the public usage model for streaming multipart reads and writes. |
| tests/test_payload.py | Shows the guarantees for byte size, streaming, replay, caching, and resource use. |
| tests/test_formdata.py | Shows the guarantees for form mode selection, field metadata, and repeated form generation. |
| tests/test_multipart.py | Shows the guarantees for boundaries, metadata parsing, nested bodies, encoding, decoding, release behavior, and streaming reader payloads. |