Part 12 / Topic 3 of 11
Making requests with urllib.request
urllib.request is in the standard library, so it needs no install. urlopen() sends the request and gives back a response object. Use it in a with block so the connection is closed. json.load(response) reads the body and turns the JSON into Python dicts and lists.
Think of urlopen as posting a letter and waiting at the door for the reply.
GET with query parameters
import json
import urllib.parse
import urllib.request
import local_api # the fake API (run inside examples/)
server, base_url = local_api.start_server()
params = urllib.parse.urlencode({"category": "kitchen", "max_price": 500})
url = f"{base_url}/api/products?{params}"
with urllib.request.urlopen(url, timeout=5) as response:
print(response.status) # 200
print(response.headers["Content-Type"]) # application/json
data = json.load(response)
print(data["count"]) # 2
print([p["name"] for p in data["products"]])
# ['Steel water bottle', 'Tea strainer']
local_api.stop_server(server)
POST a JSON body
To send data, build a Request with data= (bytes), a Content-Type header and method="POST".
import json
import urllib.request
import local_api
server, base_url = local_api.start_server()
body = json.dumps({"product_id": 2, "quantity": 2}).encode("utf-8") # str -> bytes
request = urllib.request.Request(
base_url + "/api/orders",
data=body,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=5) as response:
print(response.status) # 201
print(json.load(response))
# {'order_id': 101, 'product': 'Pressure cooker', 'quantity': 2, 'total': 3798}
local_api.stop_server(server)
Timeouts and errors
- Always pass
timeout=(seconds). Without it, a server that never answers can freeze your program forever. urllib.error.HTTPError: the server answered, but with a 4xx or 5xx code. It has.code, and you can read its body like a response.urllib.error.URLError: you could not reach the server at all (no internet, wrong host, nobody listening)..reasonsays why.TimeoutError: the server was too slow to answer.HTTPErroris a child ofURLError(Part 6), so catchHTTPErrorfirst.
import json
import urllib.error
import urllib.request
import local_api
server, base_url = local_api.start_server()
try:
urllib.request.urlopen(base_url + "/api/products/99", timeout=5)
except urllib.error.HTTPError as error:
print(error.code, json.load(error)) # 404 {'error': 'Product not found'}
try:
urllib.request.urlopen(base_url + "/api/slow", timeout=0.3)
except TimeoutError:
print("Too slow") # Too slow
local_api.stop_server(server)
try:
urllib.request.urlopen(base_url + "/api/products", timeout=5)
except urllib.error.URLError as error:
print("Cannot connect:", error.reason)
# Cannot connect: [Errno 111] Connection refused (the text differs on Windows/macOS)
Full program: examples/02_urllib_get_post.py (GET, POST, an API key header, every kind of error).
๐ Going deeper: a timeout while connecting comes as a
URLErrorwhose.reasonis aTimeoutError; a timeout while waiting for the answer is a plainTimeoutError. The fake API runs in a background thread (Stage 3) so your code and the server can run at the same time.
Read more: the official urllib.request documentation.
Done here? The practice set for Part 12 โ 8 exercises with solutions โ is on the part page.