python-hyper / h2

Pure-Python HTTP/2 protocol implementation
https://python-hyper.org/
MIT License
968 stars 157 forks source link

[Question] How can I send a POST request? #1260

Closed martin-thoma closed 3 years ago

martin-thoma commented 3 years ago

I'm trying to communicate with the Apple Push Notification service (APN) which uses HTTP/2 (docs).

I've (sucessfully) used hyper before for that with code that roughly looks like this:

from hyper import HTTPConnection
import json

bearer_token = "foo"
device_token = "bar"
payload = {}

request_headers = {
    "apns-expiration": "0",
    "apns-priority": "10",
    "authorization": f"bearer {bearer_token}",
}

conn = HTTPConnection("api.development.push.apple.com:443")
conn.request(
    "POST", f"/3/device/{device_token}",
    json.dumps(payload).encode(),
    headers=request_headers
)
resp = conn.get_response()
print(resp.status)
print(resp.reason)
print(resp.read())

How would an equivalent with h2 look like?

Kriechi commented 3 years ago

h2 itself is just a bare-bones sans-io library. Meaning, you need to handle your own I/O operations and understand the HTTP/2 protocol to make sense of the emitted events from h2. A good starting point is also the first code snippet in our main README file and our HTTP client examples: https://python-hyper.org/projects/hyper-h2/en/stable/examples.html#example-clients

If you want a fully-fledged HTTP library to send requests and read responses, I suggest https://www.python-httpx.org/ (which we also recommend as hyper replacement)

martin-thoma commented 3 years ago

I wanted to use httpx, but it didn't work: