Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
GET Request Query Parameters with Flask using python
Flask, a lightweight web framework for Python, provides developers with an intuitive and efficient way to handle GET request query parameters. When users interact with web applications, query parameters are often sent as part of the URL, conveying additional information to the server. With Flask, extracting and utilizing these query parameters becomes a seamless process.
This article will explore GET request query parameters with Flask and Python. We will demonstrate practical examples that showcase how to effectively extract and manipulate query parameter data in your Flask applications.
Understanding GET Requests and Query Parameters
GET requests are a fundamental part of the HTTP protocol and are primarily used for retrieving data from a server. Query parameters serve as key?value pairs appended to the URL, supplying supplementary information to the server. For example, in the URL http://localhost:5000/user?name=John&age=25, the query parameters are name=John and age=25.
Setting Up Flask
First, install Flask using pip ?
pip install flask
Then create a basic Flask application ?
from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def home():
return "Welcome to Flask Query Parameters Demo!"
if __name__ == '__main__':
app.run(debug=True)
Extracting Query Parameters
Flask provides the request.args object to access query parameters from GET requests. Here's how to extract and use them ?
from flask import Flask, request
app = Flask(__name__)
@app.route('/user')
def get_user_details():
name = request.args.get('name')
age = request.args.get('age')
return f"Name: {name}, Age: {age}"
if __name__ == '__main__':
app.run(debug=True)
When you visit http://localhost:5000/user?name=John&age=25, the output will be ?
Name: John, Age: 25
Handling Missing Parameters
You can provide default values for missing parameters using the get() method ?
from flask import Flask, request
app = Flask(__name__)
@app.route('/profile')
def user_profile():
name = request.args.get('name', 'Guest')
age = request.args.get('age', 'Unknown')
city = request.args.get('city', 'Not specified')
return f"Name: {name}, Age: {age}, City: {city}"
if __name__ == '__main__':
app.run(debug=True)
Visiting http://localhost:5000/profile?name=Alice will show ?
Name: Alice, Age: Unknown, City: Not specified
Multiple Values and Lists
When the same parameter appears multiple times, use getlist() to retrieve all values ?
from flask import Flask, request
app = Flask(__name__)
@app.route('/search')
def search_items():
query = request.args.get('q', '')
categories = request.args.getlist('category')
if not query:
return "Please provide a search query using ?q=your_search_term"
result = f"Searching for: '{query}'"
if categories:
result += f" in categories: {', '.join(categories)}"
return result
if __name__ == '__main__':
app.run(debug=True)
Visiting http://localhost:5000/search?q=laptop&category=electronics&category=computers will show ?
Searching for: 'laptop' in categories: electronics, computers
Parameter Validation Example
Here's a practical example that validates and processes query parameters ?
from flask import Flask, request
app = Flask(__name__)
@app.route('/calculate')
def calculate():
try:
num1 = request.args.get('a', type=int)
num2 = request.args.get('b', type=int)
operation = request.args.get('op', 'add')
if num1 is None or num2 is None:
return "Error: Please provide both 'a' and 'b' parameters as numbers"
if operation == 'add':
result = num1 + num2
elif operation == 'subtract':
result = num1 - num2
elif operation == 'multiply':
result = num1 * num2
elif operation == 'divide':
if num2 == 0:
return "Error: Cannot divide by zero"
result = num1 / num2
else:
return "Error: Supported operations are add, subtract, multiply, divide"
return f"Result: {num1} {operation} {num2} = {result}"
except ValueError:
return "Error: Parameters 'a' and 'b' must be valid numbers"
if __name__ == '__main__':
app.run(debug=True)
Visiting http://localhost:5000/calculate?a=10&b=5&op=multiply will show ?
Result: 10 multiply 5 = 50
Query Parameter Methods Comparison
| Method | Usage | Returns |
|---|---|---|
request.args.get('key') |
Get single value with default None | String or None |
request.args.get('key', 'default') |
Get single value with custom default | String or default value |
request.args['key'] |
Direct access (raises error if missing) | String or KeyError |
request.args.getlist('key') |
Get all values for repeated parameters | List of strings |
Conclusion
Flask makes handling GET request query parameters straightforward using request.args. Use get() for single values with defaults, getlist() for multiple values, and always validate user input. This approach enables you to build interactive web applications that effectively process user?provided data through URL parameters.
