Skip to main content

Request

The request object used by default in Flask. It is what ends up as flask.request. If you want to replace the request object used you can subclass this and set Flask.request_class to your subclass. The request object is a werkzeug.wrappers.Request subclass and provides all of the attributes Werkzeug defines plus a few Flask specific ones.

Attributes

url_rule

The internal URL rule that matched the request. This can be useful to inspect which methods are allowed for the URL from a before/after handler (request.url_rule.methods). Though if the request’s method was invalid for the URL rule, the valid list is available in routing_exception.valid_methods instead (an attribute of the Werkzeug exception werkzeug.exceptions.MethodNotAllowed) because the request was never internally bound.
  • Type: Rule | None
  • Added in: 0.6

view_args

A dict of view arguments that matched the request. If an exception happened when matching, this will be None.
  • Type: dict[str, Any] | None

routing_exception

If matching the URL failed, this is the exception that will be raised / was raised as part of the request handling. This is usually a werkzeug.exceptions.NotFound exception or something similar.
  • Type: HTTPException | None

Properties

max_content_length

request.max_content_length -> int | None
The maximum number of bytes that will be read during this request. If this limit is exceeded, a 413 werkzeug.exceptions.RequestEntityTooLarge error is raised. If it is set to None, no limit is enforced at the Flask application level. However, if it is None and the request has no Content-Length header and the WSGI server does not indicate that it terminates the stream, then no data is read to avoid an infinite stream. Each request defaults to the MAX_CONTENT_LENGTH config, which defaults to None. It can be set on a specific request to apply the limit to that specific view. This should be set appropriately based on an application’s or view’s specific needs. Changed in 3.1: This can be set per-request. Changed in 0.6: This is configurable through Flask config.

max_form_memory_size

request.max_form_memory_size -> int | None
The maximum size in bytes any non-file form field may be in a multipart/form-data body. If this limit is exceeded, a 413 werkzeug.exceptions.RequestEntityTooLarge error is raised. If it is set to None, no limit is enforced at the Flask application level. Each request defaults to the MAX_FORM_MEMORY_SIZE config, which defaults to 500_000. It can be set on a specific request to apply the limit to that specific view. This should be set appropriately based on an application’s or view’s specific needs. Changed in 3.1: This is configurable through Flask config.

max_form_parts

request.max_form_parts -> int | None
The maximum number of fields that may be present in a multipart/form-data body. If this limit is exceeded, a 413 werkzeug.exceptions.RequestEntityTooLarge error is raised. If it is set to None, no limit is enforced at the Flask application level. Each request defaults to the MAX_FORM_PARTS config, which defaults to 1_000. It can be set on a specific request to apply the limit to that specific view. This should be set appropriately based on an application’s or view’s specific needs. Changed in 3.1: This is configurable through Flask config.

endpoint

request.endpoint -> str | None
The endpoint that matched the request URL. This will be None if matching failed or has not been performed yet. This in combination with view_args can be used to reconstruct the same URL or a modified URL.

blueprint

request.blueprint -> str | None
The registered name of the current blueprint. This will be None if the endpoint is not part of a blueprint, or if URL matching failed or has not been performed yet. This does not necessarily match the name the blueprint was created with. It may have been nested, or registered with a different name.

blueprints

request.blueprints -> list[str]
The registered names of the current blueprint upwards through parent blueprints. This will be an empty list if there is no current blueprint, or if URL matching failed. Added in: 2.0.1

Common Request Attributes (from Werkzeug)

The Flask Request object inherits from Werkzeug’s Request class and provides access to the following common attributes:

Request Data

args

The parsed URL parameters (query string).
@app.route('/search')
def search():
    query = request.args.get('q', '')
    page = request.args.get('page', 1, type=int)
    return f"Searching for: {query}, page {page}"

form

The form parameters from POST or PUT requests.
@app.route('/login', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    return f"Username: {username}"

files

The uploaded files.
@app.route('/upload', methods=['POST'])
def upload():
    file = request.files.get('file')
    if file:
        file.save(f'/uploads/{file.filename}')
    return 'File uploaded'

data

The raw request body data as bytes.
@app.route('/webhook', methods=['POST'])
def webhook():
    raw_data = request.data
    return 'Webhook received'

json

The parsed JSON data from the request body. Returns None if the request doesn’t contain JSON data.
@app.route('/api/users', methods=['POST'])
def create_user():
    data = request.json
    username = data.get('username')
    email = data.get('email')
    return {'id': 123, 'username': username}

cookies

A dictionary of cookies sent with the request.
@app.route('/profile')
def profile():
    session_id = request.cookies.get('session_id')
    return f"Session: {session_id}"

Request Metadata

method

The HTTP method (GET, POST, PUT, DELETE, etc.).
@app.route('/item', methods=['GET', 'POST'])
def item():
    if request.method == 'POST':
        return 'Creating item'
    return 'Getting item'

headers

The request headers.
@app.route('/info')
def info():
    user_agent = request.headers.get('User-Agent')
    auth = request.headers.get('Authorization')
    return f"User-Agent: {user_agent}"

url

The full URL of the request.
@app.route('/current-url')
def current_url():
    return f"Current URL: {request.url}"

base_url

The URL without query string.

path

The path portion of the URL.

host

The host (domain) from the request.

remote_addr

The IP address of the client.
@app.route('/visitor')
def visitor():
    ip = request.remote_addr
    return f"Your IP: {ip}"

scheme

The URL scheme (http or https).

is_secure

True if the request is over HTTPS.

Methods

get_json()

request.get_json(
    force: bool = False,
    silent: bool = False,
    cache: bool = True
) -> Any | None
Parse the request body as JSON.
force
bool
default:"False"
Ignore the mimetype and always try to parse JSON
silent
bool
default:"False"
Return None instead of raising an error on parse failure
cache
bool
default:"True"
Cache the parsed JSON data
@app.route('/api/data', methods=['POST'])
def api_data():
    data = request.get_json()
    # or with options
    data = request.get_json(force=True, silent=True)
    return data

on_json_loading_failed()

request.on_json_loading_failed(e: ValueError | None) -> Any
Called if JSON parsing fails. In debug mode, this will re-raise the original error. Otherwise, it raises a generic BadRequest error.

Example Usage

from flask import Flask, request

app = Flask(__name__)

@app.route('/search')
def search():
    # Access query parameters
    query = request.args.get('q', '')
    page = request.args.get('page', 1, type=int)
    
    # Access request metadata
    user_agent = request.headers.get('User-Agent')
    ip_address = request.remote_addr
    
    # Check current endpoint and blueprint
    endpoint = request.endpoint  # 'search'
    blueprint = request.blueprint  # None or blueprint name
    
    return {
        'query': query,
        'page': page,
        'user_agent': user_agent,
        'ip': ip_address
    }

@app.route('/upload', methods=['POST'])
def upload():
    # Access form data
    title = request.form.get('title')
    
    # Access uploaded files
    file = request.files.get('file')
    if file:
        file.save(f'/uploads/{file.filename}')
    
    # Access JSON data
    if request.is_json:
        data = request.get_json()
    
    return {'status': 'success'}

@app.route('/api/users', methods=['POST'])
def create_user():
    # Set request-specific limits
    request.max_content_length = 1024 * 1024  # 1MB
    
    data = request.json
    username = data.get('username')
    
    return {'id': 123, 'username': username}

Build docs developers (and LLMs) love