0
0
Flaskframework~5 mins

Request object properties in Flask

Choose your learning style9 modes available
Introduction

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.

When you want to get data sent from a web form.
When you need to read query parameters from a URL.
When you want to check the type of HTTP method used (GET, POST, etc.).
When you want to access headers or cookies sent by the client.
When you want to handle file uploads from a user.
Syntax
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.

Examples
This example gets the 'name' field from a form sent by POST and greets the user.
Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/submit', methods=['POST'])
def submit():
    name = request.form['name']
    return f'Hello, {name}!'
This example reads a query parameter 'q' from the URL like /search?q=flask.
Flask
@app.route('/search')
def search():
    query = request.args.get('q')
    return f'Searching for: {query}'
This example shows how to get the HTTP method and a header from the request.
Flask
@app.route('/info')
def info():
    method = request.method
    user_agent = request.headers.get('User-Agent')
    return f'Method: {method}, Agent: {user_agent}'
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.