Handling the Flask Request Object and Parsing HTTP Data

The request object in Flask serves as a global proxy to the current context's request data. Designed to be thread-safe, it ensures that even in a multi-threaded environment, the data accessed belongs specifically to the active request being handled by that thread.

from flask import Flask, request

app = Flask(__name__)

@app.route('/api/inspect', methods=['GET', 'POST'])
def inspect_request():
    print(f"Request Method: {request.method}")
    print(f"Headers: {request.headers}")
    print(f"Path: {request.path}")
    print(f"Full URL: {request.url}")
    print(f"Client Address: {request.remote_addr}")
    print(f"Cookies: {request.cookies}")
    return "Data logged to console"

if __name__ == '__main__':
    app.run(debug=True)

The following client script demonstrates how to send a request with cookies to the endpoint defined above:

import requests

session_info = {'user_token': 'xy789zw'}
response = requests.get('http://127.0.0.1:5000/api/inspect', cookies=session_info)
print(response.text)

Flask distinguishes between different types of request payloads using specific attributes of the request object. Below are examples of how to handle URL query strings, form-encoded data, and JSON payloads.

from flask import Flask, request

app = Flask(__name__)

# Handling URL parameters (GET)
@app.route('/search', methods=['GET'])
def search_query():
    # request.args contains the parameters from the query string
    query = request.args.get('q')
    page = request.args.get('page', default=1, type=int)
    print(f"Search Query: {query}, Page: {page}")
    return "Search parameters processed"

# Handling Form Data (POST)
@app.route('/login', methods=['POST'])
def login_user():
    # request.form is used for data sent as application/x-www-form-urlencoded
    username = request.form.get('username')
    password = request.form.get('password')
    print(f"Login Attempt - User: {username}")
    return "Login data received"

# Handling JSON Payload (POST)
@app.route('/update-profile', methods=['POST'])
def update_profile():
    # request.get_() parses the incoming JSON string
    _data = request.get_()
    user_id = _data.get('id')
    preferences = _data.get('settings', {})
    print(f"Updating Profile for ID {user_id} with settings: {preferences}")
    return "JSON profile data processed"

if __name__ == '__main__':
    app.run(port=5000, debug=True)

Corresponding client code to test these endpoints:

import requests

base_url = 'http://127.0.0.1:5000'

# 1. Sending GET parameters
params = {'q': 'flask tutorial', 'page': 2}
resp1 = requests.get(f"{base_url}/search", params=params)
print(f"GET Status: {resp1.status_code}")

# 2. Sending Form Data
form_creds = {'username': 'dev_admin', 'password': 's3cr3t'}
resp2 = requests.post(f"{base_url}/login", data=form_creds)
print(f"Form Status: {resp2.status_code}")

# 3. Sending JSON Payload
_update = {
    'id': 42,
    'settings': {
        'notifications': True,
        'theme': 'dark'
    }
}
resp3 = requests.post(f"{base_url}/update-profile", =_update)
print(f"JSON Status: {resp3.status_code}")

Tags: Flask python web development HTTP

Posted on Sun, 17 May 2026 09:06:34 +0000 by MrAdam