Pro
Pro

Reputation: 101

get payload of a POST request flask python

I want to use the payload of a post request in another function . I tried everything in this post to read the payload of the post request.

I get this error

raise JSONDecodeError("Expecting value", s, err.value)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

My code:

    @app.route('/resource', methods = ['POST'])
    def do_something():
    data = str(request.get_data().decode('utf-8'))
    print(data)
    # output --> firstName=Sara&lastName=Laine
    res = json.dumps(data)
    another_function(res)
    return jsonify(data) 



  

Upvotes: 0

Views: 2525

Answers (2)

Leo Qi
Leo Qi

Reputation: 567

It is raising that error because request.get_data() does not return anything for the JSON module to decode. Don't use request.get_data(), use request.args

from flask import Flask, request

app = Flask(__name__)

@app.route('/resource', methods=('POST'))
def do_something():
    name = {
        'firstName': request.args.get('firstName'), # = Sara
        'lastName': request.args.get('lastName')    # = Laine
    }

    # -- Your code here --

Or, if you must use JSON:

from flask import Flask, request

app = Flask(__name__)

@app.route('/resource', methods=('POST'))
def do_something():
    name = json.dumps({
        'firstName': request.args.get('firstName'), # = Sara
        'lastName': request.args.get('lastName')    # = Laine
    })

    another_function(name)
    return name

    

Upvotes: 3

Lambo
Lambo

Reputation: 1174

You don`t need to convert the request to string and then try and dump it to json. You can convert the request.form to a dictionary and then pass the dictionary to another function

@app.route('/resource', methods = ['POST'])
def do_something():
    data = request.form
    another_function(dict(data))
    return jsonify(data)

def another_function(requestForm):
    firstName = requestForm.get("firstName")
    lastName = requestForm.get("lastName")
    print(f"{firstName} {lastName}")

Alternatively you can just pass the parameters that will be required by another function by calling the get function on the request.form:

@app.route('/resource', methods = ['POST'])
def do_something():
    data = request.form
    another_function(data.get("firstName"), data.get("lastName"))
    return jsonify(data)

def another_function(name, surname):
    print(f"{name} {surname}")

Upvotes: 0

Related Questions