Introducing a new way to review your PRs.

Read the announcement

aio-libs / aiohttp

Asynchronous HTTP client/server framework for asyncio and Python

View on GitHub

19 documents · Updated Nov 23, 2026

docs / http-parsing-and-writing

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:

  1. The request path reads the method, target, and version. It supports origin-form targets, proxy absolute-form targets, the OPTIONS * form, and authority-form CONNECT targets. The response path reads the version, three-digit status, and optional reason.
  2. Shared header processing validates names and values. It provides normalized headers for application code and raw pairs for consumers that need wire values.
  3. 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 conditionBody treatmentEnd signal
Body-forbidden method or statusEmpty payloadMessage headers
Positive Content-LengthRead the declared byte countDeclared length
Transfer-Encoding: chunkedDecode chunks and trailersZero-size chunk and trailers
CONNECT requestExpose tunnel bytesProtocol switch handling
Response with no length or transfer marker and EOF modeRead until the peer closes the connectionEOF
Supported upgradeFinish the HTTP message firstRemaining 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:

  • Connection selects close or keep-alive behavior and can signal an upgrade.
  • Upgrade selects a supported protocol switch.
  • Content-Encoding selects automatic response-body decompression when enabled. ASCII encoding names are matched without regard to case.
  • Transfer-Encoding selects chunk processing. It cannot appear with Content-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:

  1. The response layer chooses body length, chunking, compression, and connection behavior.
  2. The writer validates and buffers the status line and headers.
  3. Body writes pass through compression and length handling, then use plain or chunked wire bytes.
  4. write_eof() flushes compression, sends final body data, emits the chunk terminator when needed, and prevents later output.
  5. 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 areaMeaning
Start lineThe request method, target, status, or version is invalid. HTTPS bytes on an HTTP port receive a specific method error.
HeadersA field, line, count, required header, duplicate singleton, or framing combination is invalid.
Fixed lengthEOF arrived before the declared body length.
Transfer encodingA chunk size, chunk boundary, trailer, or chunked body end is invalid or incomplete.
Content encodingThe decoder is unavailable, the compressed data is invalid, or the compressed stream ends early.
WritingHeader 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

TriggerConsequenceGuard
Transfer-Encoding and Content-Length appear togetherThe parser cannot identify a safe body boundaryReject the message before body delivery
A duplicate singleton header appears in strict modeMessage meaning can become ambiguousReject the duplicate before creating the message
A fixed-length body ends before its declared sizeThe next message boundary is unknownRaise ContentLengthError at EOF
A chunk size, terminator, or trailer has a bad boundaryBody data can be confused with framing or the next messageRaise a transfer-encoding error and stop normal parsing
HTTP/1.1 request omits HostThe request is invalid and is not dispatchedRequire Host during message parsing
A request target contains a control characterURL interpretation can become unsafe or ambiguousReject the target before URL parsing
Header or status data contains forbidden controlsA field can split or alter the wire messageReject during parsing and serialization
A supported encoding chain has more than two codingsDecompression amplification can exceed the intended boundReject the chain when auto-decompression is enabled
Compressed input ends before a decoder reaches a stream boundaryThe body can appear complete while bytes are missingRaise ContentEncodingError at payload EOF
Output exceeds a declared fixed lengthThe peer receives bytes outside the stated messageClip writes to the remaining length
The transport closes during outputThe message cannot complete on the wireRaise ClientConnectionResetError

Key files

FileWhy to read it
aiohttp/http_parser.pyReference behavior for message lines, headers, body framing, trailers, and decompression.
aiohttp/_http_parser.pyxAccelerated parser path and its mapping to the shared message, flow-control, upgrade, and error contract.
aiohttp/http_writer.pyHeader serialization and body output rules for length, chunking, compression, EOF, and drain.
docs/http-transport.mdParent page for how parser and writer results fit into connection lifecycle.
docs/stream-flow-control.mdRelated page for payload buffering, pause, resume, and transport back-pressure.