PYTHON · PYTHON FOR EVERYONE · CHAPTER 15

Interacting with the web

Query websites and REST APIs from Python with urllib.request, and test everything against your own lab server.

10 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you already know how to open a socket and send bytes, but speaking HTTP by hand, with its headers and status codes, would be slow and error-prone. Point B: by the end of this chapter, you'll make GET and POST requests with urllib.request, send headers, handle errors, authentication and cookies, and consume a REST API that returns JSON, shaped just like RESTCONF.

From urllib2 to urllib.request

The book used 2 modules, urllib and urllib2, with functions spread across both. Python 3 reorganized them into a package, urllib, with more clearly named submodules:

Python 2 (book)Python 3.14What for
urllib2.urlopen, Request, handlersurllib.requestOpening URLs and making requests
urllib2.HTTPError, URLErrorurllib.errorExceptions
urllib.urlencode, quoteurllib.parseBuilding and parsing URLs
urllib.urlretrieveurllib.request.urlretrieveDownloading to a file (legacy interface)
httplibhttp.clientLow-level HTTP client
cookielibhttp.cookiejarCookie handling
Python 3.14 update. The book's code (import urllib2, except HTTPError, e:, print f.read()) doesn't work in Python 3. The names changed as shown in the table, exceptions are caught with as, the response is read as bytes and has to be decoded, and POST data must be sent as bytes. The Gopher support the book mentioned no longer exists, and the old URLopener and FancyURLopener classes were removed in 3.14.

Your lab: a local HTTP server

To practice without depending on the internet or a real device, you'll start a server on your own machine with the standard library's http.server module. It imitates 4 things: a text page, an echo that returns what you send, a login that hands out a cookie and an API protected with a username and password.

The API follows the structure of RESTCONF (RFC 8040), the protocol many network devices use to expose their configuration over HTTP. It uses the /restconf/data/ path, the application/yang-data+json content type and the standard ietf-interfaces model. It's a teaching simulation, not a real device.

import base64
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit

USER, PASSWORD = "lab", "lab123"
AUTHORIZED = "Basic " + base64.b64encode(f"{USER}:{PASSWORD}".encode()).decode()
IF_PATH = "/restconf/data/ietf-interfaces:interfaces"
INTERFACES = {
    "GigabitEthernet1": {"type": "iana-if-type:ethernetCsmacd", "enabled": True},
    "Loopback0": {"type": "iana-if-type:softwareLoopback", "enabled": True},
}


class Lab(BaseHTTPRequestHandler):
    def reply(self, code, body=None, ctype="application/json", extra=None):
        data = b"" if body is None else body.encode("utf-8")
        self.send_response(code)
        if body is not None:
            self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        for key, value in (extra or {}).items():
            self.send_header(key, value)
        self.end_headers()
        self.wfile.write(data)

    def read_body(self):
        length = int(self.headers.get("Content-Length", 0))
        return self.rfile.read(length).decode("utf-8")

    def authorized(self):
        if self.headers.get("Authorization") == AUTHORIZED:
            return True
        self.reply(401, '{"error": "credentials required"}',
                   extra={"WWW-Authenticate": 'Basic realm="lab"'})
        return False

    def do_GET(self):
        url = urlsplit(self.path)
        if url.path == "/":
            self.reply(200, "Hello from the lab\n", "text/plain; charset=utf-8")
        elif url.path == "/echo":
            info = {"params": parse_qs(url.query),
                    "user_agent": self.headers.get("User-Agent"),
                    "cookie": self.headers.get("Cookie")}
            self.reply(200, json.dumps(info, ensure_ascii=False))
        elif url.path == IF_PATH:
            if self.authorized():
                items = [{"name": n, **data} for n, data in INTERFACES.items()]
                body = {"ietf-interfaces:interfaces": {"interface": items}}
                self.reply(200, json.dumps(body), "application/yang-data+json")
        else:
            self.reply(404, '{"error": "not found"}')

    def do_POST(self):
        form = parse_qs(self.read_body())
        if self.path == "/login" and form == {"user": [USER], "password": [PASSWORD]}:
            self.reply(200, '{"login": "ok"}', extra={"Set-Cookie": "session=abc123; Path=/"})
        else:
            self.reply(403, '{"login": "rejected"}')

    def do_PATCH(self):
        name = self.path.removeprefix(IF_PATH + "/interface=")
        if name not in INTERFACES:
            self.reply(404, '{"error": "not found"}')
        elif self.authorized():
            changes = json.loads(self.read_body())["ietf-interfaces:interface"]
            INTERFACES[name]["enabled"] = changes["enabled"]
            self.reply(204)


with ThreadingHTTPServer(("127.0.0.1", 8000), Lab) as server:
    print("HTTP lab at http://127.0.0.1:8000 (Ctrl+C to quit)")
    server.serve_forever()

You don't need to understand every line of the server right now: the chapter's focus is the client. Save it as lab_server.py, run it in a terminal and leave it open. Run the rest of the examples from another terminal. Each request shows up in the server's log, so you can see what arrives:

$ python3 lab_server.py
HTTP lab at http://127.0.0.1:8000 (Ctrl+C to quit)
127.0.0.1 - - [24/Oct/2026 18:15:40] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [24/Oct/2026 18:15:40] "GET /missing HTTP/1.1" 404 -

If you restart the server, the API goes back to its initial state: the data lives in memory.

Reading a URL with urlopen()

urllib.request.urlopen() makes a request and returns a response object that behaves like a file opened in binary mode. It has read(), readline() and readlines(), and you can loop over it with for. There's a socket underneath, but you don't have to touch it.

The response also carries useful information: status and reason with the HTTP code, headers with the headers and geturl() with the final URL, which differs from the one you requested if there was a redirect. Use it with with to close the connection.

from urllib.request import urlopen

with urlopen("http://127.0.0.1:8000/", timeout=5) as response:
    print(response.status, response.reason)
    print(response.geturl())
    print(response.headers["Content-Type"])
    print(response.read().decode("utf-8"))
200 OK
http://127.0.0.1:8000/
text/plain; charset=utf-8
Hello from the lab

read() returns bytes: just like with sockets, you decode to get text. The timeout keeps your script from hanging if the server doesn't respond. Besides HTTP, urlopen() supports HTTPS, FTP and file: URLs; with HTTPS, it verifies the server's certificate by default.

Errors: HTTPError and URLError

2 exceptions from the urllib.error module cover almost everything. URLError means there was no response: the server doesn't exist, refuses the connection or the name doesn't resolve. Its reason attribute explains the cause.

HTTPError is a subclass of URLError: there was a response, but with an error code like 404 or 500. It has code, reason and headers. Since it's a subclass, catch it first; otherwise, the except URLError would grab it earlier.

from urllib.error import HTTPError, URLError
from urllib.request import urlopen

for url in ["http://127.0.0.1:8000/missing", "http://127.0.0.1:8001/"]:
    try:
        with urlopen(url, timeout=5) as response:
            print(response.status)
    except HTTPError as e:
        print("HTTP error:", e.code, e.reason)
    except URLError as e:
        print("Couldn't connect:", e.reason)
HTTP error: 404 Not Found
Couldn't connect: [Errno 111] Connection refused

Nobody is listening on port 8001, hence the Connection refused you already saw in the sockets chapter. If the timeout runs out, you may also get a TimeoutError.

GET parameters and POST forms

A URL doesn't accept just any character: spaces, accented letters or & must be encoded. urllib.parse.urlencode() takes a dictionary, or a list of tuples, and produces the encoded key=value&key=value string.

In a GET request, those parameters go in the URL itself, after a ?:

import json
from urllib.parse import urlencode
from urllib.request import urlopen

params = urlencode({"device": "R1", "command": "show ip route"})
print(params)

with urlopen("http://127.0.0.1:8000/echo?" + params, timeout=5) as response:
    data = json.loads(response.read())
print(data["params"])
print(data["user_agent"])
device=R1&command=show+ip+route
{'device': ['R1'], 'command': ['show ip route']}
Python-urllib/3.14

The last line is the User-Agent header that urllib sends by default. You'll see how to change it in a moment.

In a POST request, the data travels in the request body, not in the URL. Just pass the data parameter to urlopen(): when it gets it, the request becomes a POST. data must be bytes, so you encode the string from urlencode().

from urllib.parse import urlencode
from urllib.request import urlopen

data = urlencode({"user": "lab", "password": "lab123"}).encode("utf-8")

with urlopen("http://127.0.0.1:8000/login", data=data, timeout=5) as response:
    print(response.status)
    print(response.headers["Set-Cookie"])
    print(response.read().decode("utf-8"))
200
session=abc123; Path=/
{"login": "ok"}

Using POST doesn't hide the password: over HTTP, it travels across the network in plain text. With real devices, always use HTTPS and don't write credentials in your code; read them, for example, from an environment variable.

Headers with Request

To control the request further, you build a Request object and pass it to urlopen(). Besides the URL, it accepts data, a headers dictionary and method to choose the HTTP verb: GET, POST, PUT, PATCH or DELETE.

A typical case is identifying your script with the User-Agent header. Another is Accept, which tells the server which format you want the response in.

import json
from urllib.request import Request, urlopen

request = Request(
    "http://127.0.0.1:8000/echo",
    headers={"User-Agent": "thor-inventory/1.0", "Accept": "application/json"},
)
print(request.get_method(), request.full_url)

with urlopen(request, timeout=5) as response:
    print(json.loads(response.read())["user_agent"])
GET http://127.0.0.1:8000/echo
thor-inventory/1.0

Openers and handlers: authentication and proxies

Under the hood, urlopen() uses an opener, an OpenerDirector object that chains several handlers. Each handler takes care of one task: HTTP, HTTPS, redirects, proxies, authentication or cookies.

To add behavior, you create your own opener with build_opener() and pass it the extra handlers. Then you use it with its open() method, or install it globally with install_opener() so that urlopen() always uses it.

First, look at what the API returns if you call it without credentials:

from urllib.error import HTTPError
from urllib.request import urlopen

try:
    urlopen("http://127.0.0.1:8000/restconf/data/ietf-interfaces:interfaces", timeout=5)
except HTTPError as e:
    print(e.code, e.reason, e.headers["WWW-Authenticate"])
401 Unauthorized Basic realm="lab"

The 401 with WWW-Authenticate is how the server asks for HTTP basic authentication. HTTPBasicAuthHandler answers that challenge: it stores the credentials in a password manager and, when it gets the 401, repeats the request with the Authorization header. With HTTPPasswordMgrWithDefaultRealm and None as the realm, the credentials work for any realm at that URL. You use it in the next section.

Proxies work the same way. By default, urllib reads the configuration from the http_proxy and https_proxy environment variables. To set it in code, you add a ProxyHandler with a protocol → proxy URL dictionary, for example ProxyHandler({"http": "http://proxy.example.local:3128"}). For Digest authentication there's also HTTPDigestAuthHandler and, for a proxy, ProxyBasicAuthHandler and ProxyDigestAuthHandler.

A REST API with JSON, RESTCONF style

This is where it all comes together. A REST API exposes resources at URLs and uses HTTP verbs to operate on them: GET to read, PATCH to modify a part, and others. Responses arrive as JSON, which the json module turns into Python dictionaries and lists.

The script reads the interfaces, disables Loopback0 with a PATCH and reads them again. Notice that the PATCH body is JSON encoded to bytes and that the Content-Type header declares its format.

import json
from urllib.request import (HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm,
                            Request, build_opener)

BASE = "http://127.0.0.1:8000/restconf/data"
CTYPE = "application/yang-data+json"

passwords = HTTPPasswordMgrWithDefaultRealm()
passwords.add_password(None, "http://127.0.0.1:8000/", "lab", "lab123")
opener = build_opener(HTTPBasicAuthHandler(passwords))


def list_interfaces():
    request = Request(f"{BASE}/ietf-interfaces:interfaces", headers={"Accept": CTYPE})
    with opener.open(request, timeout=5) as response:
        data = json.load(response)
    for interface in data["ietf-interfaces:interfaces"]["interface"]:
        status = "enabled" if interface["enabled"] else "disabled"
        print(f"{interface['name']:<18}{status}")


list_interfaces()

change = {"ietf-interfaces:interface": {"name": "Loopback0", "enabled": False}}
request = Request(
    f"{BASE}/ietf-interfaces:interfaces/interface=Loopback0",
    data=json.dumps(change).encode("utf-8"),
    headers={"Content-Type": CTYPE},
    method="PATCH",
)
with opener.open(request, timeout=5) as response:
    print("PATCH:", response.status, response.reason)

list_interfaces()
GigabitEthernet1  enabled
Loopback0         enabled
PATCH: 204 No Content
GigabitEthernet1  enabled
Loopback0         disabled

json.load() reads straight from the response object, because it behaves like a file. The 204 code means the change was applied and there's no body to return.

With a real device, the address, the port (usually HTTPS on 443) and the credentials change, and the available YANG models depend on the vendor and version. Always check its documentation. The structure of the code, however, stays the same.

Cookies with http.cookiejar

Many web applications remember your session with cookies: the server sends Set-Cookie, and the client returns it with every following request. By default, urlopen() doesn't keep cookies. To do that, you add an HTTPCookieProcessor with a CookieJar from the http.cookiejar module.

import json
from http.cookiejar import CookieJar
from urllib.parse import urlencode
from urllib.request import HTTPCookieProcessor, build_opener

jar = CookieJar()
opener = build_opener(HTTPCookieProcessor(jar))

data = urlencode({"user": "lab", "password": "lab123"}).encode("utf-8")
opener.open("http://127.0.0.1:8000/login", data=data, timeout=5).close()

for number, cookie in enumerate(jar):
    print(number, cookie.name, cookie.value, cookie.domain)

with opener.open("http://127.0.0.1:8000/echo", timeout=5) as response:
    print("The server received:", json.load(response)["cookie"])
0 session abc123 127.0.0.1
The server received: session=abc123

The CookieJar is iterable: looping over it is the clearest way to inspect the cookies you received. The second request shows that the opener sent the cookie on its own. If you ever need to add a cookie by hand, there's set_cookie(), although building the Cookie object is tedious. To save cookies to disk between runs, there's MozillaCookieJar.

Downloading to a file

To save the content of a URL to disk, urlretrieve() does it in one line and returns the path and the headers. It's a function inherited from the old urllib interface, and the documentation warns that it might become deprecated. The recommended alternative combines urlopen() with shutil.copyfileobj(), which copies in chunks without loading everything into memory:

import shutil
from urllib.request import urlopen, urlretrieve

path, headers = urlretrieve("http://127.0.0.1:8000/", "welcome.txt")
print(path, headers["Content-Length"])

with urlopen("http://127.0.0.1:8000/", timeout=5) as response, \
        open("welcome2.txt", "wb") as target:
    shutil.copyfileobj(response, target)

with open("welcome2.txt", encoding="utf-8") as f:
    print(f.read(), end="")
welcome.txt 19
Hello from the lab

Beyond the standard library: requests and httpx

urllib.request ships with Python and needs no installation, an advantage on servers where you can't add packages. The trade-off is that it's verbose. Python's own documentation recommends the requests package for a higher-level HTTP interface. Another common option is httpx, with a similar API that adds async support and, optionally, HTTP/2.

Both are third-party libraries: you install them from PyPI, ideally inside a virtual environment.

$ python3 -m venv .venv
$ source .venv/bin/activate
(.venv) $ python -m pip install requests httpx

Here's the interface query with requests. Authentication, headers and JSON conversion fit in a few lines:

import requests

BASE = "http://127.0.0.1:8000/restconf/data"

response = requests.get(
    f"{BASE}/ietf-interfaces:interfaces",
    auth=("lab", "lab123"),
    headers={"Accept": "application/yang-data+json"},
    timeout=5,
)
response.raise_for_status()
for interface in response.json()["ietf-interfaces:interfaces"]["interface"]:
    print(interface["name"], interface["enabled"])
GigabitEthernet1 True
Loopback0 False

Loopback0 shows up as False because the server remembers the earlier PATCH. raise_for_status() raises an exception if the HTTP code is an error. With httpx, the same code works if you change requests.get to httpx.get.

Challenge

Answer before you open the solution.

1. You're migrating a script with import urllib2. Where do you import urlopen, urlencode and HTTPError from in Python 3?

From urllib.request, urllib.parse and urllib.error, respectively.

2. You pass data=urlencode(data) to urlopen() and it fails with TypeError. What's missing?

Encoding to bytes. urlencode() returns str; the request body must be bytes: urlencode(data).encode("utf-8").

3. You write except URLError before except HTTPError. What happens with a 404?

The URLError block catches it. HTTPError is a subclass of URLError, so the more specific exception must come first.

4. How do you make a PATCH request with urllib.request?

With Request(url, data=..., method="PATCH"). Without method, a request with data would be a POST.

5. An API responds with 401 and the WWW-Authenticate: Basic header. Which handler deals with it?

HTTPBasicAuthHandler, with a password manager like HTTPPasswordMgrWithDefaultRealm, inside an opener created with build_opener().

Key takeaways

  • urllib2 and urllib became urllib.request, urllib.parse and urllib.error; cookielib is now http.cookiejar.
  • urlopen() returns a file-like object of bytes with status, headers and geturl(). Use with and timeout.
  • Catch HTTPError before URLError.
  • GET carries the parameters in the URL; POST, in data as bytes. urlencode() encodes them.
  • Request gives you headers and the method; handlers add authentication, proxies and cookies.
  • You consume a REST API with JSON using Request + json; requests and httpx make it simpler.

In the next chapter, you'll run tasks in parallel with threads, for example querying several devices at once instead of one after another.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate