http2.md
This file
Path
docs/http2.md
68 lines · 2.5 KiB · Markdown
Last changed by
Revert "Removed leading $ from cli code blocks" (#3192)Tom Christiebefore adoptionf06171f
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# HTTP/2
HTTP/2 is a major new iteration of the HTTP protocol, that provides a far moreefficient transport, with potential performance benefits. HTTP/2 does not changethe core semantics of the request or response, but alters the way that data issent to and from the server.
Rather than the text format that HTTP/1.1 uses, HTTP/2 is a binary format.The binary format provides full request and response multiplexing, and efficientcompression of HTTP headers. The stream multiplexing means that where HTTP/1.1requires one TCP stream for each concurrent request, HTTP/2 allows a single TCPstream to handle multiple concurrent requests.
HTTP/2 also provides support for functionality such as response prioritization,and server push.
For a comprehensive guide to HTTP/2 you may want to check out "[http2 explained](https://http2-explained.haxx.se/)".
## Enabling HTTP/2
When using the `httpx` client, HTTP/2 support is not enabled by default, becauseHTTP/1.1 is a mature, battle-hardened transport layer, and our HTTP/1.1implementation may be considered the more robust option at this point in time.It is possible that a future version of `httpx` may enable HTTP/2 support by default.
If you're issuing highly concurrent requests you might want to considertrying out our HTTP/2 support. You can do so by first making sure to installthe optional HTTP/2 dependencies...
```shell$ pip install httpx[http2]```
And then instantiating a client with HTTP/2 support enabled:
```pythonclient = httpx.AsyncClient(http2=True)...```
You can also instantiate a client as a context manager, to ensure that allHTTP connections are nicely scoped, and will be closed once the context blockis exited.
```pythonasync with httpx.AsyncClient(http2=True) as client: ...```
HTTP/2 support is available on both `Client` and `AsyncClient`, although it'stypically more useful in async contexts if you're issuing lots of concurrentrequests.
## Inspecting the HTTP version
Enabling HTTP/2 support on the client does not *necessarily* mean that yourrequests and responses will be transported over HTTP/2, since both the client*and* the server need to support HTTP/2. If you connect to a server that onlysupports HTTP/1.1 the client will use a standard HTTP/1.1 connection instead.
You can determine which version of the HTTP protocol was used by examiningthe `.http_version` property on the response.
```pythonclient = httpx.AsyncClient(http2=True)response = await client.get(...)print(response.http_version) # "HTTP/1.0", "HTTP/1.1", or "HTTP/2".```