Skip to content
Myr

http2.md

This file

Path

docs/http2.md

60 lines · 2.2 KiB · Markdown

Last changed by

Better HTTP/2 defaults. (#584)Tom Christiebefore adoption30229f1

History of this file

Take it

Better HTTP/2 defaults. (#584)Tom Christiebefore adoption30229f1

lines 1–60why, one step back
1# HTTP/2
23HTTP/2 is a major new iteration of the HTTP protocol, that provides a far more4efficient transport, with potential performance benefits. HTTP/2 does not change5the core semantics of the request or response, but alters the way that data is6sent to and from the server.78Rather that the text format that HTTP/1.1 uses, HTTP/2 is a binary format.9The binary format provides full request and response multiplexing, and efficient10compression of HTTP headers. The stream multiplexing means that where HTTP/1.111requires one TCP stream for each concurrent request, HTTP/2 allows a single TCP12stream to handle multiple concurrent requests.1314HTTP/2 also provides support for functionality such as response prioritization,15and server push.1617For a comprehensive guide to HTTP/2 you may want to check out "[HTTP2 Explained](https://http2-explained.haxx.se/content/en/)".1819## Enabling HTTP/22021The HTTPX client provides provisional HTTP/2 support.2223HTTP/2 support is not enabled by default, because HTTP/1.1 is a mature,24battle-hardened transport layer. With HTTP/2 being newer and significantly more25complex, our implementation should be considered a less robust option at this26point in time.2728However, if you're issuing highly concurrent requests you might want to consider29trying out our HTTP/2 support. You can do so by instantiating a client with30HTTP/2 support enabled:3132```python33client = httpx.Client(http_2=True)34...35```3637You can also instantiate a client as a context manager, to ensure that all38HTTP connections are nicely scoped, and will be closed once the context block39is exited.4041```python42async with httpx.Client(http_2=True) as client:43 ...44```4546## Inspecting the HTTP version4748Enabling HTTP/2 support on the client does not *necessarily* mean that your49requests and responses will be transported over HTTP/2, since both the client50*and* the server need to support HTTP/2. If you connect to a server that only51supports HTTP/1.1 the client will use a standard HTTP/1.1 connection instead.5253You can determine which version of the HTTP protocol was used by examining54the `.http_version` property on the response.5556```python57client = httpx.Client(http_2=True)58response = await client.get(...)59print(response.http_version) # "HTTP/1.0", "HTTP/1.1", or "HTTP/2".60```