Python Fetching Data from the Web with urllib
What you will learn
- How a web request works in outline
- Taking URLs apart and building them with
urllib.parse urlopen, the response, and reading JSON- Headers, query strings, POST requests
- Errors:
HTTPError,URLError, timeouts - Retrying and good manners with other people's servers
1. Requests and responses
When a browser or a program asks for a web page or data, it sends a request to a server and gets a response. A request has a method (GET to fetch, POST to send data), a URL, and headers; a response has a status code (200 = OK, 404 = not found, 500 = server error), headers and a body of bytes. This is the HTTP protocol.
Python's standard library can make requests with the urllib package. (Most programmers install the third-party requests library for comfort, lesson 16.6, but urllib needs nothing and teaches the same ideas.)
About these examples. To keep the lesson repeatable and respectful of real websites, every example below talks to a tiny web server started on your own computer (
127.0.0.1, port chosen automatically). No data left the computer when they were checked. The worked example contains the server code, so you can run everything offline. For a real site, you replace the address with its URL.
import json
import urllib.error
import urllib.parse
import urllib.request
2. The parts of a URL
urllib.parse takes URLs apart and builds them safely:
u = urllib.parse.urlparse("https://example.com:8080/a/b?x=1&y=2#top")
print(u.scheme, u.netloc, u.hostname, u.port)
print(u.path, u.query, u.fragment)
https example.com:8080 example.com 8080
/a/b x=1&y=2 top
| Part | Example | Meaning |
|---|---|---|
| scheme | https |
the protocol (https is encrypted) |
| host and port | example.com, 8080 |
which server |
| path | /a/b |
which resource |
| query | x=1&y=2 |
extra parameters |
| fragment | top |
a place inside the page (never sent to the server) |
Build a query string with urlencode, which escapes special characters for you, and read one with parse_qs:
q = urllib.parse.urlencode({"q": "python tips", "page": 2, "lang": "bn&en"})
print(q)
print(urllib.parse.parse_qs(q))
q=python+tips&page=2&lang=bn%26en
{'q': ['python tips'], 'page': ['2'], 'lang': ['bn&en']}
The space became + and the & inside a value became %26, so it could not be confused with the separator. Never join parameters by hand with +. Related helpers:
print(urllib.parse.urljoin("https://example.com/a/b", "../c"))
print(urllib.parse.quote("a b/ΓΌ"), urllib.parse.unquote("a%20b"))
https://example.com/c
a%20b/%C3%BC a b
Quick check: why use `urlencode` instead of writing `"?q=" + text`?
urlencode escapes spaces, &, = and non-ASCII characters so the value arrives intact; manual joining breaks on such characters.
3. Making a GET request
urllib.request.urlopen(url) sends the request and returns a response object. Use it in a with block so the connection is closed (lesson 14.6):
with urllib.request.urlopen(BASE + "/data?x=1") as r:
print(r.status, r.reason, r.headers["Content-Type"])
raw = r.read()
print(type(raw), raw)
print(json.loads(raw.decode("utf-8")))
200 OK application/json
<class 'bytes'> b'{"path": "/data?x=1", "agent": "Python-urllib/3.13"}'
{'path': '/data?x=1', 'agent': 'Python-urllib/3.13'}
(BASE stands for the local server's address, such as http://127.0.0.1:50321.)
r.statusandr.reasongive the status code and its text;r.headersholds the response headers.r.read()returns the body as bytes (lesson 15.8). Decode it with the right encoding (utf-8for most modern data) to get text.- Because the data is JSON,
json.load(r)can read straight from the response (lesson 15.7). - The server saw the default
User-AgentheaderPython-urllib/3.13, which tells it what kind of program is asking.
Headers and Request objects
To set headers (or a method, or a body), build a Request object:
req = urllib.request.Request(BASE + "/data", headers={"User-Agent": "lesson/1.0"})
with urllib.request.urlopen(req, timeout=5) as r:
print(json.load(r))
{'path': '/data', 'agent': 'lesson/1.0'}
Many real services want an identifying User-Agent, an Accept header, or an Authorization header with a key. Keep keys out of your source code (use an environment variable, lesson 17.7).
4. Sending data: POST
To send data, give the Request a data argument (bytes) and say what it is:
body = json.dumps({"name": "Rina"}).encode("utf-8")
req = urllib.request.Request(BASE + "/post", data=body,
headers={"Content-Type": "application/json"},
method="POST")
with urllib.request.urlopen(req) as r:
print(r.status, json.load(r))
201 {'got': {'name': 'Rina'}, 'ctype': 'application/json'}
The server replied 201 Created with the JSON it had received. Forms use urllib.parse.urlencode(...) for the body with the content type application/x-www-form-urlencoded.
5. When things go wrong
Two exception families (lesson 14.2), both in urllib.error:
| Exception | Meaning |
|---|---|
HTTPError |
the server replied, but with an error status (404, 500...) |
URLError |
the request could not be made: server not found, connection refused, timed out |
HTTPError is a kind of URLError, and URLError is a kind of OSError. Catch the specific one first:
try:
urllib.request.urlopen(BASE + "/missing")
except urllib.error.HTTPError as e:
print("HTTPError:", e.code, e.reason, e.read())
try:
urllib.request.urlopen("http://127.0.0.1:1/", timeout=2)
except urllib.error.URLError as e:
print("URLError:", type(e.reason).__name__)
HTTPError: 404 Not Found b'nope'
URLError: TimeoutError
(On the computer used for this check, nothing answered on port 1, so the attempt timed out; on another system the reason may be ConnectionRefusedError, which is why printing type(e.reason) is worth doing.) An HTTPError has code, reason and also a body you can read().
Always set a timeout
Without a timeout, a request to a silent server can wait forever. Pass timeout=seconds:
try:
urllib.request.urlopen(BASE + "/slow", timeout=0.3)
except (TimeoutError, urllib.error.URLError) as e:
print("timeout:", type(e).__name__)
timeout: TimeoutError
(The "slow" page waited 2 seconds before answering.) Set a timeout on every request.
6. Retrying, and good manners
Networks are unreliable. A sensible client:
- retries a few times on temporary failures (network errors, status 500, 502, 503) but not on mistakes that will repeat (404, 400, 401);
- waits between attempts (
time.sleep, lesson 17.1), often longer each time; - sets a timeout and a clear User-Agent;
- respects the website's terms of use and
robots.txt, and does not send a flood of requests: ask for what you need, cache results (lesson 17.5), and keep a pause between calls; - never sends passwords or keys over plain
http://, and prefershttps://; - does not trust the data it receives: validate it (lesson 14.5).
Large or complex jobs (sessions, cookies, uploads, authentication, JSON helpers) are far easier with the third-party requests or httpx libraries, installed with pip.
Worked example: a client with retries, against a local server
The script starts a tiny server in a thread, with /users (a list, optionally limited by ?limit=), /flaky (fails twice with 503 then succeeds) and anything else gives 404. get_json builds the URL safely, sets a timeout, retries server errors only, and gives up on client errors.
import http.server
import json
import threading
import urllib.error
import urllib.parse
import urllib.request
class Handler(http.server.BaseHTTPRequestHandler):
attempts = 0
def do_GET(self):
path = urllib.parse.urlparse(self.path)
if path.path == "/users":
query = urllib.parse.parse_qs(path.query)
limit = int(query.get("limit", ["10"])[0])
users = [{"id": i, "name": f"user{i}"} for i in range(1, 6)][:limit]
self.reply(200, users)
elif path.path == "/flaky":
Handler.attempts += 1
if Handler.attempts < 3:
self.reply(503, {"error": "busy"})
else:
self.reply(200, {"ok": True, "attempt": Handler.attempts})
else:
self.reply(404, {"error": "not found"})
def reply(self, status, data):
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
BASE = f"http://127.0.0.1:{server.server_address[1]}"
def get_json(path, params=None, retries=3, timeout=5):
url = BASE + path
if params:
url += "?" + urllib.parse.urlencode(params)
for attempt in range(1, retries + 1):
try:
with urllib.request.urlopen(url, timeout=timeout) as response:
return json.load(response)
except urllib.error.HTTPError as e:
if e.code < 500 or attempt == retries:
raise
print(f" server error {e.code}, attempt {attempt} of {retries}")
except urllib.error.URLError as e:
if attempt == retries:
raise
print(f" network problem ({e.reason}), attempt {attempt}")
print(get_json("/users", {"limit": 2}))
print(get_json("/flaky"))
try:
get_json("/nothing")
except urllib.error.HTTPError as e:
print("gave up:", e.code, e.reason)
server.shutdown()
[{'id': 1, 'name': 'user1'}, {'id': 2, 'name': 'user2'}]
server error 503, attempt 1 of 3
server error 503, attempt 2 of 3
{'ok': True, 'attempt': 3}
gave up: 404 Not Found
| Part | Idea |
|---|---|
urlencode({"limit": 2}) |
the query string is built safely |
timeout=timeout |
no request can hang forever |
except HTTPError first, then URLError |
specific before general (lesson 14.1) |
if e.code < 500 ... raise |
a 404 is our mistake, so we do not retry; a 503 is temporary, so we do |
with ... as response |
the connection is always closed |
| a server in a thread | the whole lesson runs offline, repeatable, and harms nobody |
The users and responses are made up. A real client would wait a little between attempts with time.sleep.
Common mistakes
- No timeout on requests.
- Building query strings by hand.
- Treating the response as text (it is bytes: decode it).
- Retrying errors that will never succeed (404, 401).
- Ignoring errors or catching
Exceptionand moving on. - Hammering a server with rapid requests, or ignoring its rules.
- Sending secrets over
http://or putting keys in source code. - Trusting downloaded data without validating it.
Key takeaways
urllib.request.urlopen(url, timeout=...)makes a GET request and returns a response withstatus,headersand a bytes body;json.load(response)reads JSON directly.urllib.parsesplits URLs and builds query strings safely (urlencode,parse_qs).- A
Requestobject adds headers, a method and a body (POST). HTTPErrormeans the server answered with an error;URLErrormeans no answer; always set a timeout.- Retry temporary failures with pauses, not permanent ones; be polite, use
https, protect keys, and validate what you receive. - Third-party
requestsandhttpxare more convenient for large jobs.
Practice
1. What type does response.read() return?
Show answer
bytes. Decode with .decode("utf-8"), or pass the response to json.load.
2. What is the difference between HTTPError and URLError?
Show answer
HTTPError means the server replied with an error status such as 404; URLError means the request could not be completed at all (no connection, timeout). HTTPError is a subclass of URLError.
3. Why always pass timeout?
Show answer
Without it, a server that never answers can make the program wait forever.
4. Build the URL https://api.example.com/search?q=a+b&page=2 from parts.
Show answer
"https://api.example.com/search?" + urllib.parse.urlencode({"q": "a b", "page": 2})
5. Which of 404 and 503 deserves a retry?
Show answer
503 (service unavailable) is temporary, so retry after a pause. A 404 (not found) will stay the same.
6. How do you send a JSON body in a POST with urllib?
Show answer
Encode it to bytes and pass it as data to a Request with method="POST" and the header Content-Type: application/json, then call urlopen(request).