The request object in Flask holds all the information sent by the client to the server. It helps you understand what the user wants and how to respond.
Request object properties in Flask
from flask import request # Access form data request.form['fieldname'] # Access query parameters request.args.get('param') # Check HTTP method request.method # Access headers request.headers.get('Header-Name') # Access cookies request.cookies.get('cookie_name') # Access JSON data request.get_json() # Access uploaded files request.files['filefield']
The request object is available inside your route functions.
Use request.method to know if the user sent a GET or POST request.
from flask import Flask, request app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): name = request.form['name'] return f'Hello, {name}!'
@app.route('/search') def search(): query = request.args.get('q') return f'Searching for: {query}'
@app.route('/info') def info(): method = request.method user_agent = request.headers.get('User-Agent') return f'Method: {method}, Agent: {user_agent}'
This Flask app has one route '/greet' that works with both GET and POST. It reads the 'name' from form data if POST, or from query parameters if GET, and greets the user accordingly.
from flask import Flask, request app = Flask(__name__) @app.route('/greet', methods=['GET', 'POST']) def greet(): if request.method == 'POST': name = request.form.get('name', 'Guest') return f'Hello, {name}! You sent a POST request.' else: name = request.args.get('name', 'Guest') return f'Hello, {name}! You sent a GET request.' if __name__ == '__main__': app.run(debug=True)
Always check if the key exists in request.form or request.args to avoid errors.
Use request.get_json() if you expect JSON data instead of request.json for better error handling.
Remember to set the correct HTTP methods in your route decorator to accept POST or other methods.
The request object holds all client data sent to your Flask app.
You can get form data, query parameters, headers, cookies, and files from it.
Check request.method to know how the data was sent.
Practice
request.method in Flask represent?Solution
Step 1: Understand the role of
This property tells you which HTTP method the client used to send the request, such as GET or POST.request.methodStep 2: Differentiate from other request properties
It is not the URL path, IP address, or response code, which are accessed differently.Final Answer:
The HTTP method used by the client (GET, POST, etc.) -> Option DQuick Check:
request.method = HTTP method [OK]
- Confusing method with URL or path
- Thinking method is client IP
- Mixing method with response status
request object?Solution
Step 1: Identify how query parameters are accessed
Query parameters are part of the URL after the question mark and are accessed viarequest.args.Step 2: Use the correct method to get a parameter
Usingrequest.args.get('param')safely retrieves the value or returns None if missing.Final Answer:
request.args.get('param') -> Option AQuick Check:
Query params = request.args.get() [OK]
- Using request.form for query parameters
- Trying to get query params from cookies or headers
- Using request.args['param'] without .get() risking KeyError
{'username': 'alice'}?
from flask import Flask, request
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
user = request.form.get('username')
method = request.method
return f"User: {user}, Method: {method}"Solution
Step 1: Understand the request method and form data
The client sends a POST request with form data containing 'username' = 'alice'.Step 2: Check how data is accessed in the code
The code usesrequest.form.get('username')which retrieves 'alice', andrequest.methodwhich is 'POST'.Final Answer:
User: alice, Method: POST -> Option AQuick Check:
Form data and method match output [OK]
- Assuming method is GET when POST was sent
- Using request.args instead of request.form for POST data
- Expecting None for existing form data
request.form['email']?
@app.route('/submit', methods=['POST'])
def submit():
email = request.form['email']
return f"Email: {email}"Solution
Step 1: Understand why KeyError occurs
Accessingrequest.form['email']raises KeyError if 'email' is missing in the form data.Step 2: Suggest safer access method
Userequest.form.get('email')to avoid KeyError and get None if missing.Final Answer:
The form data might not include 'email', causing KeyError -> Option CQuick Check:
Missing key in form causes KeyError [OK]
- Assuming form always has the key
- Confusing form data with query parameters
- Thinking request.form is inaccessible
session_id in a Flask route. Which code snippet correctly checks for it and returns its value or 'No session' if missing?
A) sid = request.cookies['session_id'] return sid if sid else 'No session'B)
sid = request.cookies.get('session_id')
return sid or 'No session'
C) sid = request.form.get('session_id')
return sid or 'No session'
D) sid = request.args.get('session_id')
return sid or 'No session'Solution
Step 1: Identify how to safely access cookies
Cookies are accessed viarequest.cookies. Using.get()avoids KeyError if cookie is missing.Step 2: Return cookie value or fallback
Usingsid or 'No session'returns the cookie value if present, else the fallback string.Final Answer:
Use .get() on cookies and return fallback if missing -> Option BQuick Check:
Cookies use request.cookies.get() safely [OK]
- Accessing cookies with [] risking KeyError
- Looking for cookies in form or args
- Not providing fallback for missing cookie
Ready to prove it?
Pass the test and this pattern moves unknown
