HTTP Client Requests with urllib.request
Python's standard library includes `urllib.request`. You can perform HTTP GET requests and read remote responses directly without installing external dependencies like `requests` 🌐.
import urllib.request
# Configure request with custom User-Agent:
req = urllib.request.Request(
"https://httpbin.org/status/200",
headers={"User-Agent": "Python-Native-Client/1.0"}
)
print(f"Target URL: {req.full_url} 🌐")
print(f"Configured header: {req.get_header('User-agent')} ✅")
# 31. HTTP Client Requests with urllib.request Python's standard library includes `urllib.request`. You can perform HTTP GET requests and read remote responses directly without installing external dependencies like `requests` 🌐. ```python import urllib.request # Configure request with custom User-Agent: req = urllib.request.Request( "https://httpbin.org/status/200", headers={"User-Agent": "Python-Native-Client/1.0"} ) print(f"Target URL: {req.full_url} 🌐") print(f"Configured header: {req.get_header('User-agent')} ✅") ``` Knowing `urllib.request` is crucial when writing minimal Docker containers or Cloudflare Worker sidecars where adding heavy third-party packages slows down boot times! 🌐 --- ### Question Why should you create a `urllib.request.Request` object instead of passing a bare URL string directly to `urlopen`? 🧠 - [ ] a. It allows configuring custom HTTP headers, HTTP methods, and payload bodies 🌐 - [ ] b. Bare URLs can only fetch HTML, never JSON - [ ] c. Bare URLs are rejected by Linux kernel networking - [ ] d. It turns on WebSocket upgrades automatically --- ### Challenge Import `urllib.request`. Create `req = urllib.request.Request('https://example.com', headers={'X-App-ID': 'Antigravity'})`. Print `req.get_header('X-app-id')`. 🎯 <details> <summary>Solution</summary> ```python import urllib.request req = urllib.request.Request( "https://example.com", headers={"X-App-ID": "Antigravity"} ) print(req.get_header("X-app-id")) ``` </details>