To retrieve data received in a Flask request, you can use the following attributes available on the request
object:
from flask import request
request.args
: This attribute contains the key/value pairs from the URL query string. You can access them usingrequest.args['key']
.request.form
: This attribute contains the key/value pairs from the body of an HTML post form or a JavaScript request that isn’t JSON encoded. You can access them usingrequest.form['key']
.request.files
: If your request includes files in the body, Flask keeps them separate from the form data. HTML forms must useenctype=multipart/form-data
for file uploads. You can access the files usingrequest.files['key']
.request.values
: This attribute combines theargs
andform
attributes, giving preference toargs
if there are overlapping keys. You can access the values usingrequest.values['key']
.request.json
: If the request contains JSON data and has theapplication/json
content type, you can access the parsed JSON data usingrequest.json
. Alternatively, you can userequest.get_json(force=True)
to ignore the content type.
All of these attributes are instances of MultiDict
from the Werkzeug library, except for json
. To access values from the MultiDict
, you can use the following methods:
request.form['name']
: Use indexing if you know the key exists.request.form.get('name')
: Use theget
method if the key might not exist.request.form.getlist('name')
: Use thegetlist
method if the key is sent multiple times and you want a list of values. Theget
method only returns the first value.
In most common cases, request.data
will be empty as it is used as a fallback when Flask encounters a mime-type it doesn’t handle.
For more details, you can refer to the Flask documentation on the request
object.