As of my last update in 2023, the requests
library in Python does not natively support HTTP/2. The requests
library relies on the urllib3
library, which does not provide HTTP/2 support either. HTTP/2 support in Python is typically provided by other libraries such as httpx
or hyper
.
To perform an HTTP/2 request in Python, you can use the httpx
library, which is an async-capable HTTP client that has a similar API to requests
and supports HTTP/2.
Here's an example of how to use httpx
to perform an HTTP/2 request:
import httpx
# Create an HTTP/2 client
client = httpx.Client(http2=True)
try:
# Perform the request
response = client.get('https://www.example.com')
# Check if the response was received via HTTP/2
protocol = response.http_version
print(f'Response received via: {protocol}')
# Print the response
print(response.text)
finally:
# Close the client
client.close()
To use httpx
, you'll need to install it first. You can install httpx
using pip
:
pip install httpx
If you specifically want to stick with the requests
API and still need HTTP/2 support, you can try using the requests
adapter for HTTP/2 provided by hyper
, which is a lower-level HTTP/2 client for Python.
Here's an example of how to use hyper
with requests
to perform an HTTP/2 request:
from hyper.contrib import HTTP20Adapter
import requests
# Create a session
s = requests.Session()
# Mount the HTTP/2 adapter
s.mount('https://', HTTP20Adapter())
# Perform the request
response = s.get('https://www.example.com')
# Print the response
print(response.text)
To use this approach, you'll need to install hyper
:
pip install hyper
Please note that hyper
is not actively maintained, and its compatibility with the latest versions of requests
might be an issue. Therefore, using httpx
is usually the recommended way to make HTTP/2 requests in Python.