Flask by Example: Request Query Parameters
Query parameters are key-value pairs added to the end of a URL (e.g., ?key=value). They are commonly used for filtering, pagination, and search queries.
Code
from flask import Flask, request
app = Flask(__name__)
@app.route('/search')
def search():
# URL: /search?q=python&page=2
# 1. Get a specific parameter (returns None if missing)
query = request.args.get('q')
# 2. Get with a default value
page = request.args.get('page', 1, type=int)
# 3. Get all values for a key (e.g. ?tag=a&tag=b)
tags = request.args.getlist('tag')
if not query:
return "Please provide a search query", 400
return {
"query": query,
"page": page,
"tags": tags
}Explanation
The request object in Flask is a global object containing all client data sent with the HTTP request. To access URL query parameters (the part of the URL after the ?), you use the request.args dictionary. This allows you to retrieve inputs for filtering, searching, or pagination easily.
It is best practice to use the .get() method rather than direct dictionary access. This method returns None or a specified default value if the key is missing, preventing your application from crashing with a 400 Bad Request error when optional parameters are omitted.
Flask also provides type conversion directly within the get() method. By passing type=int, Flask will attempt to convert the value, returning the default if conversion fails. This feature simplifies input validation logic significantly, ensuring you work with the correct data types.
Code Breakdown
request.args.get('q') retrieves the value for 'q'. If the URL is just /search, variable query will be None.type=int ensures page is an integer. If the user sends ?page=abc, Flask ignores the invalid value and uses the default 1.request.args.getlist('tag') handles multiple parameters with the same name. ?tag=python&tag=flask results in ['python', 'flask']. Standard .get() would only return the first one."Message", 400 allows you to set the HTTP status code. Here we return 400 Bad Request if the required query parameter is missing.
