HTTP parsing and message writing
HTTP parsing and writing form the byte-level boundary for aiohttp's client and server flows. The parsers turn network data into a message record and a streamed body. The writer turns status, headers, and body data into valid HTTP bytes while applying the selected length, transfer, compression, and connection rules. See HTTP transport for connection ownership and stream flow control for buffer pressure.
Message parsing
The parser accepts arbitrary pieces of input and produces request or response messages with separate body streams. It preserves incomplete data until the next call. This lets one transport read contain partial messages or several messages without making read boundaries part of HTTP semantics.
Two parser paths provide the same message contract. The Python path is the reference path. The accelerated path uses a native HTTP state machine and maps its callbacks to the same raw message fields, payload behavior, upgrade rules, and error categories. The paths must remain behaviorally aligned even though their scan steps differ.
When a complete start line and header block arrive, parsing follows this sequence:
- The request path reads the method, target, and version. It supports origin-form targets, proxy absolute-form targets, the
OPTIONS *form, and authority-formCONNECTtargets. The response path reads the version, three-digit status, and optional reason. - Shared header processing validates names and values. It provides normalized headers for application code and raw pairs for consumers that need wire values.
- The parser derives connection, compression, upgrade, and transfer state. It then creates an empty payload or a body stream with the matching framing rules.
This diagram shows how incoming bytes become a message and a body stream. Bytes after the current message remain available for the next message or for an upgraded protocol.
flowchart LR
B[Incoming bytes] --> S[Start line and headers]
S --> M[Raw request or response message]
S --> R{Body framing}
R -->|No body| E[Empty payload]
R -->|Known length| L[Fixed-length payload]
R -->|Chunked| C[Chunked payload]
R -->|Connection close| F[Read until EOF]
L --> P[Stream reader]
C --> P
F --> P
M --> Q[Transport or application queue]
P --> Q
Q --> T[Remaining input]
References: aiohttp/http_parser.py• L305-641 aiohttp/_http_parser.pyx• L322-761
HTTP message semantics
Message semantics decide whether a body exists and how its end is found. The parser evaluates the method and response status before it trusts body framing headers. This prevents bytes for the next message from being read as the current body.
| Message condition | Body treatment | End signal |
|---|---|---|
| Body-forbidden method or status | Empty payload | Message headers |
Positive Content-Length | Read the declared byte count | Declared length |
Transfer-Encoding: chunked | Decode chunks and trailers | Zero-size chunk and trailers |
CONNECT request | Expose tunnel bytes | Protocol switch handling |
| Response with no length or transfer marker and EOF mode | Read until the peer closes the connection | EOF |
| Supported upgrade | Finish the HTTP message first | Remaining upgraded-protocol bytes |
HTTP/1.1 requests require Host. Keep-alive defaults differ by HTTP version and by Connection tokens. Responses close by default when their framing does not give a safe boundary. Data after a message marked Connection: close is rejected rather than treated as another message.
An upgrade is a protocol switch requested through HTTP headers. A supported request waits until its HTTP body ends before the parser returns the remaining bytes as upgraded-protocol data. A body-free upgrade can switch at once. CONNECT has its own tunnel behavior and exposes the connection after the request headers.
The parser can bound the number of complete messages waiting for application consumption. When that queue is full, it keeps the remaining input and resumes after a message is consumed. This limits pipelined request growth without changing message order.
References: aiohttp/http_parser.py• L361-365 aiohttp/http_parser.py• L471-575 aiohttp/http_parser.py• L627-641 aiohttp/_http_parser.pyx• L511-588 aiohttp/_http_parser.pyx• L1007-1025
Header processing
Header processing turns wire fields into a case-insensitive collection while retaining raw name and value pairs. It trims optional whitespace, validates field names, applies field and count limits, and uses a compatibility mode only where response parsing needs to accept common non-standard input.
Strict parsing rejects duplicate singleton fields such as Content-Length, Content-Location, Content-Range, Content-Type, ETag, Host, Max-Forwards, Server, Transfer-Encoding, and User-Agent. Response parsing is lax outside debug mode so common server responses with duplicate non-security fields remain usable. Both paths reject control characters that could change message structure. Trailer fields use the same validation rules as initial headers.
Header values also select later message behavior:
Connectionselects close or keep-alive behavior and can signal an upgrade.Upgradeselects a supported protocol switch.Content-Encodingselects automatic response-body decompression when enabled. ASCII encoding names are matched without regard to case.Transfer-Encodingselects chunk processing. It cannot appear withContent-Length.
Request and response transfer-coding rules are not identical. A request must end its transfer-coding list with chunked and cannot list chunked twice. A response uses its final transfer-coding token to decide whether the body is chunked.
References: aiohttp/http_parser.py• L74-165 aiohttp/http_parser.py• L216-295 aiohttp/http_parser.py• L643-694 aiohttp/_http_parser.pyx• L82-98 aiohttp/_http_parser.pyx• L455-491 aiohttp/_http_parser.pyx• L511-550
Body transfer and decoding
The payload path separates body framing from body delivery. It counts fixed-length data, decodes chunk sizes and trailers, or passes data until EOF. It feeds decoded body data to a stream reader and pauses when that reader cannot accept more data. This connects HTTP framing to transport flow control.
Chunked bodies use hexadecimal sizes and a line break after each data chunk. A zero-size chunk starts trailer parsing. Invalid sizes, boundaries, trailer blocks, or incomplete bodies become protocol errors. A fixed-length body is complete only after the declared bytes reach the payload stream.
Automatic decompression runs as body data is delivered. Supported encodings include gzip, deflate, Brotli, and Zstandard when their optional support is available. A supported Content-Encoding chain is limited to two codings. The decompression layer tracks compressed input, bounds output, and rejects a stream that ends before every coding reaches its end.
The payload path also keeps framing state when delivery pauses. It can resume with an empty input call, then return any bytes that follow a completed body to the message parser.
References: aiohttp/http_parser.py• L126-165 aiohttp/http_parser.py• L926-1212 aiohttp/http_parser.py• L1215-1339 aiohttp/_http_parser.pyx• L589-612 aiohttp/_http_parser.pyx• L980-1004
Message writing
The stream writer turns a status line, headers, and body writes into one HTTP message on the active transport. It buffers headers until body data or an explicit send request. This allows small headers and body data to share a write while still sending empty responses at end of message.
The writer has a Python header serializer and can use an accelerated serializer when the native extension is available. Both paths produce the same HTTP header block and reject forbidden control characters before the block reaches the transport.
The writer applies transforms in wire order. It compresses body data first, then limits or frames the bytes according to the configured message length and chunking mode. Therefore chunk sizes describe compressed bytes. A fixed length clips output at the declared boundary, while chunked output wraps each body write and ends with a zero-size marker.
The normal send flow is:
- The response layer chooses body length, chunking, compression, and connection behavior.
- The writer validates and buffers the status line and headers.
- Body writes pass through compression and length handling, then use plain or chunked wire bytes.
write_eof()flushes compression, sends final body data, emits the chunk terminator when needed, and prevents later output.- The writer drains when transport buffering reaches the active limit.
This diagram shows the boundary between application data and HTTP wire data.
flowchart LR
H[Status line and headers] --> V[Header validation and buffering]
D[Application body data] --> C{Compression enabled?}
C -->|No| L[Length handling]
C -->|Yes| K[Compressed bytes]
K --> L
L --> F{Chunked?}
F -->|No| W[Transport writes]
F -->|Yes| X[Chunk framing]
X --> W
V --> W
W --> E[Drain and end of message]
References: aiohttp/http_writer.py• L50-240 aiohttp/http_writer.py• L247-352 aiohttp/http_writer.py• L354-383
Protocol error handling
Protocol errors stop processing when message structure, body boundaries, or content decoding is unsafe or unclear. The parser reports start-line, header, framing, length, transfer, and content-encoding failures through distinct error categories so the transport and payload consumer can handle the correct failure boundary.
| Error area | Meaning |
|---|---|
| Start line | The request method, target, status, or version is invalid. HTTPS bytes on an HTTP port receive a specific method error. |
| Headers | A field, line, count, required header, duplicate singleton, or framing combination is invalid. |
| Fixed length | EOF arrived before the declared body length. |
| Transfer encoding | A chunk size, chunk boundary, trailer, or chunked body end is invalid or incomplete. |
| Content encoding | The decoder is unavailable, the compressed data is invalid, or the compressed stream ends early. |
| Writing | Header data contains forbidden controls, or the transport is already closing. |
Errors found while consuming a body are attached to the payload stream. Errors that could change the next message boundary are raised to the parser caller, so the connection does not continue with a false message. The accelerated path maps native parser failures into the same broad categories and preserves payload errors for the stream consumer.
References: aiohttp/http_parser.py• L325-340 aiohttp/http_parser.py• L551-581 aiohttp/http_parser.py• L991-1020 aiohttp/_http_parser.pyx• L638-761 aiohttp/_http_parser.pyx• L980-1017 aiohttp/_http_parser.pyx• L1050-1078 aiohttp/http_writer.py• L88-114 aiohttp/http_writer.py• L354-365
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the Python and accelerated paths aligned for raw message fields, framing flags, upgrade timing, queue pauses, and error categories.
- Keep request-target validation aligned with URL-form handling. Control characters must not reach URL interpretation in either path.
- Keep strict request parsing and lax response parsing aligned with header and line-ending safety rules.
- When the strict singleton-header set changes, check duplicate handling in both parser paths and keep response compatibility behavior intact.
- When body framing changes, update parser tail handling and writer final markers together. These boundaries control pipelining and upgrades.
- When compression changes, preserve the order of compression and chunk framing. Length and transfer headers must describe the bytes sent on the wire.
- When queue limits or payload pause behavior changes, check that resume calls neither duplicate nor discard buffered input.
- When response body rules change, check status and method cases that must not carry a body before adding framing headers.
- When header serialization changes, keep the Python and accelerated serializers aligned on control-character rejection and wire output.
- When supported content codings change, keep chain limits, optional decoder checks, stage order, and truncated-stream handling aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
Transfer-Encoding and Content-Length appear together | The parser cannot identify a safe body boundary | Reject the message before body delivery |
| A duplicate singleton header appears in strict mode | Message meaning can become ambiguous | Reject the duplicate before creating the message |
| A fixed-length body ends before its declared size | The next message boundary is unknown | Raise ContentLengthError at EOF |
| A chunk size, terminator, or trailer has a bad boundary | Body data can be confused with framing or the next message | Raise a transfer-encoding error and stop normal parsing |
HTTP/1.1 request omits Host | The request is invalid and is not dispatched | Require Host during message parsing |
| A request target contains a control character | URL interpretation can become unsafe or ambiguous | Reject the target before URL parsing |
| Header or status data contains forbidden controls | A field can split or alter the wire message | Reject during parsing and serialization |
| A supported encoding chain has more than two codings | Decompression amplification can exceed the intended bound | Reject the chain when auto-decompression is enabled |
| Compressed input ends before a decoder reaches a stream boundary | The body can appear complete while bytes are missing | Raise ContentEncodingError at payload EOF |
| Output exceeds a declared fixed length | The peer receives bytes outside the stated message | Clip writes to the remaining length |
| The transport closes during output | The message cannot complete on the wire | Raise ClientConnectionResetError |
Key files
| File | Why to read it |
|---|---|
| aiohttp/http_parser.py | Reference behavior for message lines, headers, body framing, trailers, and decompression. |
aiohttp/_http_parser.pyx | Accelerated parser path and its mapping to the shared message, flow-control, upgrade, and error contract. |
| aiohttp/http_writer.py | Header serialization and body output rules for length, chunking, compression, EOF, and drain. |
| docs/http-transport.md | Parent page for how parser and writer results fit into connection lifecycle. |
| docs/stream-flow-control.md | Related page for payload buffering, pause, resume, and transport back-pressure. |