h2: Pure-Python HTTP/2 Protocol Implementation

4.3.0 · active · verified Sat Mar 28

h2 is a pure-Python, self-contained implementation of the HTTP/2 protocol stack. It handles the low-level framing and state machine, allowing users to build HTTP/2 clients and servers without dealing with raw I/O. The library aims for 100% compatibility with RFC 7540 and is designed to be embeddable in various concurrency models. The current version is 4.3.0, and it has a regular release cadence with notable updates and breaking changes between major versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize an `H2Connection` with `H2Configuration` and send basic HTTP/2 headers. The library is purely in-memory, so managing I/O (sending and receiving bytes over a network socket) is left to the user's application.

import h2.connection
import h2.config
import os

# Example: Initialize H2Connection for a client or server
config = h2.config.H2Configuration(client_side=True) # or False for server_side
conn = h2.connection.H2Connection(config=config)

# Example of sending a request (client-side)
stream_id = conn.get_next_available_stream_id()
headers = [
    (':method', 'GET'),
    (':authority', os.environ.get('H2_EXAMPLE_AUTHORITY', 'example.com')),
    (':scheme', 'https'),
    (':path', '/')
]
conn.send_headers(stream_id=stream_id, headers=headers)
conn.end_stream(stream_id)

# Data to send over the wire (conceptual)
data_to_send = conn.data_to_send()
if data_to_send:
    # In a real application, you would send this data over a socket.
    # print(f"Sending {len(data_to_send)} bytes: {data_to_send!r}")
    pass

# Simulate receiving data and processing events
# events = conn.receive_data(received_bytes)
# for event in events:
#     if isinstance(event, h2.events.RequestReceived):
#         print(f"Request received on stream {event.stream_id}")

print("h2 connection initialized and example headers sent.")

view raw JSON →