Read query parameters from a fixture URL
Also published in our primary archive.
A URL’s query is separate from its path and fragment. This example uses a fixed fixtures.example.test URL, so it demonstrates parsing only; it makes no request. urlsplit() separates the URL into named components, and its query attribute contains the text after ? but before #. Passing that text to parse_qs() produces a dictionary whose values are lists, even when a key appears once.
The input has term=blue+sky, page=2, and an explicitly blank empty= value. parse_qs(..., keep_blank_values=True) decodes the plus sign to a space and retains the blank value. The assertions check the fixture path and the complete parsed mapping before selected values are printed. They demonstrate this particular input’s result, not that arbitrary URL input is valid.
urlsplit() does not validate a URL for an application’s security rules. If input is untrusted, check the scheme, host, path, and any application-specific limits before using the parsed result. Also, without keep_blank_values=True, empty= would be omitted. These APIs are available in Python 3.2+; the example needs no newer-version-only feature. See the official urllib.parse documentation.
AI assistance disclosure: this article was drafted with AI assistance and should be adapted to the application’s own URL rules.
from urllib.parse import parse_qs, urlsplit
fixture_url = "https://fixtures.example.test/search?term=blue+sky&page=2&empty=#results"
parts = urlsplit(fixture_url)
parameters = parse_qs(parts.query, keep_blank_values=True)
assert parts.path == "/search"
assert parameters == {
"term": ["blue sky"],
"page": ["2"],
"empty": [""],
}
print(parameters["term"][0])
print(parameters["page"][0])
print(repr(parameters["empty"][0]))
blue sky
2
''