Coder Perfect

Get the information from a Flask request.


I’d like to be able to send data to my Flask app. I attempted to access, but it returned an empty string. How do you get data from a request?

from flask import request

@app.route('/', methods=['GET', 'POST'])
def parse_request():
    data =  # data is empty
    # need posted data here

The response to this question prompted me to ask the following question: Get raw POST body in Python Flask regardless of Content-Type header, which is about retrieving raw data rather than processed data.

Asked by ddinchev

Solution #1

During a request, the documentation describe the attributes available on the request object (from flask import request). Because is utilised as a fallback in most circumstances, it will be empty.

These are all MultiDict instances (except for json). Values can be accessed by using the following methods:

Answered by Robert

Solution #2

Use to access the raw data. This only works if it couldn’t be parsed as form data; otherwise, it’ll be empty and the parsed data will be in request.form.

from flask import request

Answered by clyfish

Solution #3

Use request.args for URL query arguments.

search = request.args.get("search")
page = request.args.get("page")

Use request.form for posted form input.

email = request.form.get('email')
password = request.form.get('password')

Use request for JSON with the content type application/json. get json().

data = request.get_json()

Answered by Fizer Khan

Solution #4

Here’s an example of parsing and repeating posted JSON data.

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/foo', methods=['POST']) 
def foo():
    data = request.json
    return jsonify(data)

To use curl to post JSON, follow these steps:

curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo

Alternatively, to use Postman’s words:

Answered by Little Roys

Solution #5

Use request to access the raw post body regardless of the content type. get data(). It calls request when you use The request will be filled using get data(parse form data=True). Make a MultiDict and leave the data blank.

Answered by Xiao

Post is based on