In Flask, when a user accesses our application, they send various requests (such as GET, POST, etc.), and we need to obtain the parameters and data passed by the user in the request. This is where the request object comes into play. Flask encapsulates this information through the request object, making it easy for us to access the user’s input.
1. Importing the Request Object¶
First, we need to import the request object from Flask. In your Flask application file (for example, app.py), you’ll typically start with:
from flask import Flask, request
app = Flask(__name__)
With this, we can use request in our route functions to handle request data.
2. Retrieving Query String Parameters (URL Parameters)¶
When users pass parameters through the query string in the URL (e.g., /hello?name=Alice&age=18), these parameters are stored in the query string. Flask allows us to access them using request.args.
Example: Getting GET Parameters¶
@app.route('/hello')
def hello():
# Get the "name" parameter from the query string, defaulting to "Guest"
name = request.args.get('name', 'Guest')
# Get the "age" parameter, specifying type=int, defaulting to 0
age = request.args.get('age', 0, type=int)
return f"Hello, {name}! You are {age} years old."
When a user visits /hello?name=Bob&age=20, the page will return Hello, Bob! You are 20 years old..
request.argsis a dictionary-like object that stores all query parameters.- Use
get('parameter_name')to retrieve a parameter, with the second argument as the default value (returned if the parameter doesn’t exist). - Specify
type=int(or other types like float, str) to enforce parameter types. If the parameter is missing or has an invalid type, the default value is returned.
3. Retrieving Form Data (POST Requests)¶
When users submit data via an HTML form (e.g., a login form), they typically use a POST request. To handle this, we need to specify methods=['POST'] in the route and access the form data using request.form.
Example: Handling POST Form Submissions¶
@app.route('/login', methods=['POST'])
def login():
# Get username and password from the form
username = request.form.get('username')
password = request.form.get('password')
if username and password:
return f"Login successful! Welcome, {username}."
else:
return "Please fill in all fields.", 400 # Return 400 Bad Request
The frontend must submit data in the application/x-www-form-urlencoded format (the default for HTML forms). For example, using Postman to simulate a POST request, select form-data or x-www-form-urlencoded in the Body and enter username and password.
4. Retrieving JSON Data (POST Requests)¶
If users send JSON-formatted data via a POST request (e.g., using JavaScript’s fetch), we use request.get_json() to access it.
Example: Handling JSON Data¶
@app.route('/add_user', methods=['POST'])
def add_user():
# Check if the request is JSON
if not request.is_json:
return "Request must be JSON", 415 # 415 Unsupported Media Type
# Parse the JSON data
data = request.get_json()
username = data.get('username')
age = data.get('age')
if username and age:
return f"User {username} added. Age: {age}"
else:
return "Missing username or age", 400
The frontend should send JSON like this:
{
"username": "Charlie",
"age": 22
}
request.is_jsonchecks if the request is in JSON format.request.get_json()returns a parsed Python dictionary. If the request isn’t JSON, it returnsNone.- Use
request.get_json(force=True)to force parsing even if theContent-Typeheader isn’tapplication/json(not recommended, as it may cause errors).
5. Key Takeaways¶
- Query Strings (GET Parameters): Use
request.argsfor parameters in the URL after?. - Form Data (POST): Use
request.form; ensure the route specifiesmethods=['POST']. - JSON Data (POST): Use
request.get_json(); first check if the request is JSON withrequest.is_json. - Always provide default values when using
get()to avoidNoneerrors. - The
requestobject has other useful attributes (e.g.,request.methodfor the HTTP method,request.headersfor headers), but the above methods are most common for parameter retrieval.
Mini Exercise¶
Try modifying the examples to:
1. Create a route that gets the id parameter from the URL and returns its square (remember to handle type conversion).
2. Create a POST route that accepts JSON data and returns the length of the data.
These exercises will help you become more proficient at handling user input and parameters!