Query parameters allow clients to send additional data in the URL, typically after a ?
symbol. Parsing these parameters correctly is essential for filtering, searching, pagination, and other common web app features.
What Are Query Parameters?
A URL like /search?q=python&sort=asc
contains query parameters:
-
q
with value"python"
-
sort
with value"asc"
They are key-value pairs separated by &
after the ?
character.
Extracting Query Parameters
When your framework receives a request, the path may include a query string:
/users?id=42&active=true
You can split the path on ?
to separate the path from the query string:
path, _, query_string = full_path.partition('?')
Parsing Query Strings with urllib
Python’s built-in urllib.parse
module offers utilities:
from urllib.parse import parse_qs
def parse_query_params(query_string):
params = parse_qs(query_string)
# parse_qs returns values as lists, so simplify:
return {k: v[0] if len(v) == 1 else v for k, v in params.items()}
Example:
parse_query_params("q=python&sort=asc&tag=web&tag=python")
# returns: {'q': 'python', 'sort': 'asc', 'tag': ['web', 'python']}
Integrating Query Parsing into Requests
Add query parameters to your request object so handlers can easily access them:
request["query_params"] = parse_query_params(query_string)
Handlers can then do:
def search_handler(request):
q = request["query_params"].get("q", "")
sort = request["query_params"].get("sort", "desc")
# perform search using q and sort
return f"Results for {q} sorted {sort}"
Handling Missing or Malformed Queries
- If no
?
is present, query string is empty -
parse_qs
safely returns an empty dict on empty input - Values are URL-decoded automatically by
parse_qs
Supporting Multiple Values per Key
For keys appearing multiple times, parse_qs
returns a list. This is useful for filters:
/products?color=red&color=blue
Your handler can accept lists for flexible queries.
URL Encoding and Decoding
Clients URL-encode special characters (%20
for space, etc). parse_qs
handles decoding automatically, so your app gets clean strings.
Practical Uses
- Pagination:
?page=2&limit=10
- Search queries:
?q=keyword
- Filtering:
?category=books&price_min=10
- Sorting:
?sort=asc
Wrap-Up
Parsing URL query parameters is straightforward with Python’s standard library. Integrating this step into your lightweight framework lets your handlers accept dynamic inputs via the URL, making your apps far more interactive and useful.
Want to dive deeper? Check out my 20-page PDF guide: Building a Lightweight Python Web Framework from Scratch
Top comments (0)