Batu Lab NotesPractical developer guides

Join a relative fixture link to a base URL

By Batu · English technical notes

A relative link has no scheme or host, so it needs a base URL before it can identify a full location. urljoin() applies URL resolution rules rather than merely appending two strings. In this fixture, the base points to /catalog/2026/index.html and the relative link is guides/parsing.html?format=short#example. The resolved result replaces the final filename portion of the base path and retains the relative link’s query and fragment.

The assertion checks the exact resulting URL before the program prints it. It demonstrates how this particular file-like base and relative reference combine. A base URL ending in a slash has different path semantics because it represents a directory; choosing a fixture with index.html makes the replacement behavior explicit.

Do not treat urljoin() as a way to confine an untrusted string to a host or directory. A second argument beginning with a scheme or // is absolute and can supply its own destination. If that matters, split and reject or remove scheme and network-location components before joining. The current RFC 3986-aligned urljoin() behavior has applied since Python 3.5; this example should therefore use Python 3.5+ for those documented semantics. More examples and this limitation appear in the official urllib.parse documentation.

AI assistance disclosure: this article was drafted with AI assistance and should be reviewed when links originate outside trusted fixture data.

from urllib.parse import urljoin

base_url = "https://fixtures.example.test/catalog/2026/index.html"
relative_link = "guides/parsing.html?format=short#example"
joined_url = urljoin(base_url, relative_link)

assert joined_url == (
    "https://fixtures.example.test/catalog/2026/guides/parsing.html?format=short#example"
)

print(joined_url)
https://fixtures.example.test/catalog/2026/guides/parsing.html?format=short#example