Get the data received in a Flask request
The docs describe the attributes available on the request
object (from flask import request
) during a request. In most common cases request.data
will be empty because it's used as a fallback:
request.data
Contains the incoming request data as string in case it came with a mimetype Flask does not handle.
-
request.args
: the key/value pairs in the URL query string -
request.form
: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn't JSON encoded -
request.files
: the files in the body, which Flask keeps separate fromform
. HTML forms must useenctype=multipart/form-data
or files will not be uploaded. -
request.values
: combinedargs
andform
, preferringargs
if keys overlap -
request.json
: parsed JSON data. The request must have theapplication/json
content type, or userequest.get_json(force=True)
to ignore the content type.
All of these are MultiDict
instances (except for json
). You can access values using:
-
request.form['name']
: use indexing if you know the key exists -
request.form.get('name')
: useget
if the key might not exist -
request.form.getlist('name')
: usegetlist
if the key is sent multiple times and you want a list of values.get
only returns the first value.
To get the raw data, use request.data
. This only works if it couldn't be parsed as form data, otherwise it will be empty and request.form
will have the parsed data.
from flask import request
request.data
For URL query parameters, use request.args
.
search = request.args.get("search")
page = request.args.get("page")
For posted form input, use request.form
.
email = request.form.get('email')
password = request.form.get('password')
For JSON posted with content type application/json
, use request.get_json()
.
data = request.get_json()
Here's an example of parsing posted JSON data and echoing it back.
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/foo', methods=['POST'])
def foo():
data = request.json
return jsonify(data)
To post JSON with curl:
curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo
Or to use Postman:
To get the raw post body regardless of the content type, use request.get_data()
. If you use request.data
, it calls request.get_data(parse_form_data=True)
, which will populate the request.form
MultiDict
and leave data
empty.