Pass the dictionary to urllib.parse.urlencode(params) from Python’s built-in urllib.parse module to serialize keys and values into a percent-encoded query string ("key1=val1&key2=val2"), setting doseq=True whenever dictionary values are lists or tuples that should expand into repeated query parameters ("tag=a&tag=b").
Basic Example
from urllib.parse import urlencode
params = {
"q": "python & pandas",
"page": 2,
"category": "data science/ml",
}
# 1. Recommended: Encode a standard flat dictionary into a URL query string
query_string = urlencode(params)
print(query_string)
# Output: q=python+%26+pandas&page=2&category=data+science%2Fml
full_url = f"[https://api.example.com/search](https://api.example.com/search)?{query_string}"
print(full_url)
# Output: [https://api.example.com/search?q=python+%26+pandas&page=2&category=data+science%2Fml](https://api.example.com/search?q=python+%26+pandas&page=2&category=data+science%2Fml)
# 2. Encoding multi-value parameters (lists/tuples) using `doseq=True`:
multi_params = {"tag": ["python", "api"], "limit": 10}
print(urlencode(multi_params, doseq=True))
# Output: tag=python&tag=api&limit=10
Key Details & Edge Cases
- Space encoding (
+vs.%20viaquote_via=urllib.parse.quote):- By default,
urlencode()usesurllib.parse.quote_plus, which encodes spaces as+("hello world"$\rightarrow$"hello+world"). If your target API or RFC 3986 URI builder strictly expects%20for spaces, passquote_via=urllib.parse.quote:from urllib.parse import quote, urlencode print(urlencode({"q": "hello world"}, quote_via=quote)) # Output: q=hello%20world
- By default,
- Forgetting
doseq=Trueserializes lists as literal stringified brackets (5B...5D):- Calling
urlencode({"tag": ["a", "b"]})withoutdoseq=Trueturns the list intostr(["a", "b"]), yielding"tag=%5B%27a%27%2C+%27b%27%5D". Always passdoseq=Truewhen values can be sequences (list,tuple).
- Calling
Nonevalues serialize as the literal string"None"unless filtered first:urlencode({"filter": None})outputs"filter=None". StripNonekeys beforehand when building optional API parameters:clean_params = {k: v for k, v in params.items() if v is not None} query = urlencode(clean_params, doseq=True)
- Appending query parameters to a URL that may already contain
?or fragments ():- Rather than blindly concatenating
f"{base_url}?{urlencode(params)}"(which breaks ifbase_urlalready has?foo=1or), parse and rebuild the URL safely withurlsplit()/parse_qsl()/urlunsplit():from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit parts = urlsplit("[https://example.com/items?sort=asc#top](https://example.com/items?sort=asc#top)") merged = dict(parse_qsl(parts.query)) | {"page": 2} new_url = urlunsplit(parts._replace(query=urlencode(merged, doseq=True))) # Output: [https://example.com/items?sort=asc&page=2#top](https://example.com/items?sort=asc&page=2#top)
- Rather than blindly concatenating
- HTTP client libraries (
requests/httpx) handle dictionary encoding automatically:- If you are sending the request with
requests.get(url, params=params)orhttpx.get(url, params=params), pass the dictionary directly toparams=—do not pre-encode it withurlencode(), or the client will double-encode%signs (%20$\rightarrow$%2520).
- If you are sending the request with
Comparison of URL Query-Encoding Approaches in Python
| Method | Library | Handles Multi-Value Lists? | Space Encoding Default | Best Used When |
|---|---|---|---|---|
urllib.parse.urlencode(d, doseq=True) (Recommended) |
Built-in urllib.parse |
Yes (with doseq=True) |
+ (or %20 via quote_via=quote) |
Building query strings for urllib.request, redirects, sign-in URLs, or custom URL builders. |
requests.get(url, params=d) / httpx.get(url, params=d) |
requests / httpx (3rd-party) |
Yes (automatically) | + (handled internally) |
Making live HTTP requests without manually constructing URL strings. |
urllib.parse.quote(s, safe="") |
Built-in urllib.parse |
N/A (single string only) | %20 |
Encoding an individual URL path segment (/users/{username}) rather than key=value query pairs. |
Manual f"{k}={v}" string joining (Avoid) |
Built-in str |
Manual | Unescaped (broken URLs) | Never use—fails on reserved characters (, =, ?, +, /, spaces, and non-ASCII UTF-8 text). |
You must log in or register to comment.
