Last modified: Nov 15, 2024 By Alexander Williams

Flask Request: Accessing HTTP Request Data Made Easy

When building web applications with Flask, handling HTTP request data is crucial. Before diving into request handling, ensure you have Flask properly installed in your environment.

Accessing Form Data

Flask's request.form object allows you to access data submitted through HTML forms. Here's how to handle form submissions:


from flask import Flask, request

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def handle_form():
    username = request.form.get('username')
    password = request.form.get('password')
    return f'Received: {username}'

Query Parameters

Using request.args helps you access URL query parameters. This is particularly useful when dealing with GET requests.


@app.route('/search')
def search():
    query = request.args.get('q', '')
    return f'Search query: {query}'

JSON Data Handling

For API development, request.json is essential for handling JSON data in requests. Make sure to specify the correct content type in your requests.


@app.route('/api/data', methods=['POST'])
def handle_json():
    data = request.json
    return {'received': data}

Request Headers

Access request headers using request.headers. This is useful for handling authentication tokens or content negotiation.


@app.route('/headers')
def get_headers():
    user_agent = request.headers.get('User-Agent')
    return f'Your browser: {user_agent}'

File Uploads

Handle file uploads with request.files. Make sure to validate file types and implement proper security measures.


@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return 'No file uploaded'
    file = request.files['file']
    return f'File received: {file.filename}'

Testing Request Examples

Here's how you might see the output when testing these endpoints:


# Form submission response
Received: johndoe

# Search query response
Search query: flask tutorial

# JSON response
{"received": {"message": "Hello, World!"}}

Best Practices and Security

Always validate and sanitize input data. Use proper error handling and implement CSRF protection for form submissions.

Conclusion

Understanding request handling is fundamental for Flask development. For more advanced routing techniques, check out our Flask routing guide.