Search code examples
pythonjsonrestflaskflask-restful

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.

#way1
return request.data["test"]

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

#way2
test["test"]

#error message: TypeError: expected string or buffer

Solution

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

    request.get_json()

    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)
        else:
            return jsonify(status="Request was not JSON")