Flask Request Parsing
Every incoming request carries data. Flask's request object gives you access to all of it — URL parameters, form fields, JSON bodies, uploaded files, and headers. Understanding the request object lets you extract exactly what you need from any type of request.
The Request Object
Flask makes the request object available inside every view function. It represents the current HTTP request and holds all data the client sent.
from flask import request
@app.route('/inspect')
def inspect():
print(request.method) # 'GET', 'POST', etc.
print(request.path) # '/inspect'
print(request.url) # 'http://127.0.0.1:5000/inspect'
print(request.remote_addr) # client IP address
return 'Inspected!'Request Data by Source
| Data Source | Access Via | Example |
|---|---|---|
| URL query string | request.args | /search?q=flask&page=2 |
| HTML form POST | request.form | Form with method="POST" |
| JSON body | request.get_json() | API requests with JSON payload |
| Uploaded files | request.files | File input fields |
| Request headers | request.headers | Authorization, Content-Type |
| Cookies | request.cookies | Browser-stored cookies |
| Raw body bytes | request.data | Binary payloads, XML |
Query String Parameters
@app.route('/search')
def search():
keyword = request.args.get('q', '')
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 10, type=int)
category = request.args.get('category')
# URL: /search?q=flask&page=2&per_page=5&category=tutorials
return f'Searching for "{keyword}", page {page}'The third argument to .get() is the type to convert to. Flask returns the default value if the parameter is missing or cannot be converted to the specified type.
Form Data (POST)
@app.route('/register', methods=['POST'])
def register():
username = request.form.get('username', '').strip()
email = request.form.get('email', '').lower()
password = request.form.get('password')
terms = request.form.get('terms') # checkbox
skills = request.form.getlist('skills') # multiple checkboxes
country = request.form.get('country', 'us') # select dropdownJSON Request Body
@app.route('/api/login', methods=['POST'])
def api_login():
data = request.get_json()
if data is None:
return jsonify({'error': 'Expected JSON body'}), 400
email = data.get('email')
password = data.get('password')
if not email or not password:
return jsonify({'error': 'email and password required'}), 400
# authenticate...
return jsonify({'token': 'abc123'}), 200request.get_json() returns None if the request body is not valid JSON or if the Content-Type header is not application/json. Pass force=True to parse JSON regardless of the Content-Type header:
data = request.get_json(force=True, silent=True) # silent=True returns None instead of errorReading Headers
@app.route('/api/data')
def protected_data():
auth_header = request.headers.get('Authorization', '')
if not auth_header.startswith('Bearer '):
return jsonify({'error': 'Missing token'}), 401
token = auth_header.split(' ')[1]
# validate token...
return jsonify({'data': 'secret information'})Checking Content Type
@app.route('/api/create', methods=['POST'])
def create():
if request.content_type != 'application/json':
return jsonify({'error': 'Content-Type must be application/json'}), 415
data = request.get_json()
# process...Combining Multiple Sources
@app.route('/api/items', methods=['POST'])
def create_item():
# From URL: /api/items?notify=true
notify = request.args.get('notify', 'false') == 'true'
# From JSON body
data = request.get_json() or {}
name = data.get('name')
# From header
user_agent = request.headers.get('User-Agent', '')
return jsonify({
'name': name,
'notify': notify,
'client': user_agent[:50]
}), 201Summary
Flask's request object provides access to all data in an incoming request. Use request.args for query string parameters, request.form for HTML form data, request.get_json() for JSON API bodies, request.files for uploads, and request.headers for HTTP headers. Always use .get() with a default value so missing fields do not cause exceptions.
