Custom HTTP Headers & JSON Payloads
To send a POST request with `urllib.request`, encode a dictionary to JSON bytes (`json.dumps(d).encode()`), pass it as `data`, and set header Content-Type to application/json 📡.
import urllib.request, json
payload = {"action": "sync", "timestamp": 1700000000}
encoded_bytes = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
"https://api.example.com/v1/events",
data=encoded_bytes, # Passing bytes triggers HTTP POST! 📡
headers={"Content-Type": "application/json"}
)
print(f"HTTP Method: {req.get_method()} 🚀")
print(f"Content-Type: {req.get_header('Content-type')} 📋")
# 32. Custom HTTP Headers & JSON Payloads To send a POST request with `urllib.request`, encode a dictionary to JSON bytes (`json.dumps(d).encode()`), pass it as `data`, and set header `'Content-Type': 'application/json'` 📡. ```python import urllib.request, json payload = {"action": "sync", "timestamp": 1700000000} encoded_bytes = json.dumps(payload).encode("utf-8") req = urllib.request.Request( "https://api.example.com/v1/events", data=encoded_bytes, # Passing bytes triggers HTTP POST! 📡 headers={"Content-Type": "application/json"} ) print(f"HTTP Method: {req.get_method()} 🚀") print(f"Content-Type: {req.get_header('Content-type')} 📋") ``` Remember: HTTP transports raw octets over TCP sockets, so always pass encoded `.encode("utf-8")` bytes, never raw Python strings! 📡 --- ### Question What triggers `urllib.request.Request` to switch its HTTP method from GET to POST? 🧠- [ ] a. Providing non-None bytes to the `data` parameter in `Request` 🚀 - [ ] b. Setting the User-Agent header to 'POST' - [ ] c. Passing an integer port number - [ ] d. Calling `req.set_post_true()` --- ### Challenge Create a POST request using `urllib.request.Request` containing JSON bytes for `{"status": "OK"}` and header `{"Content-Type": "application/json"}`. Print `req.get_method()`. 🎯 <details> <summary>Solution</summary> ```python import urllib.request, json data = json.dumps({"status": "OK"}).encode("utf-8") req = urllib.request.Request( "https://api.example.com", data=data, headers={"Content-Type": "application/json"} ) print(req.get_method()) ``` </details>