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.