[FIXED] Python-flask extracting values from a POST request to REST API


I am trying to extract values from a JSON payload by POST request:

Question 1:
What is a better way to get the data?

First Way?

@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        test = request.data
        return test

or Second Way?

@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        test = json.loads(request.json)
        return test

Question 2:
How do I get a specific value?

Given the json payload is:

{ "test": "hello world" }

I tried doing code below, but does not work.

return request.data["test"]

#error message: TypeError: string indices must be integers, not str


#error message: TypeError: expected string or buffer


If you are posting JSON to a flask endpoint you should use:


A very important API note:

By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter

Meaning… either make sure the mimetype of the POST is application/json OR be sure to set the force option to true

A good design would put this behind:

request.is_json like this:

@app.route('/post/', methods=['POST'])
def post():
    if request.is_json:
        data = request.get_json()
        return jsonify(data)
        return jsonify(status="Request was not JSON")

Answered By – abigperson

Answer Checked By – Pedro (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published