0

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) 



  
Pro
  • 81
  • 1
  • 9

2 Answers2

3

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

    
Renato Byrro
  • 3,578
  • 19
  • 34
Leo Qi
  • 557
  • 5
  • 13
  • Where is the `request` name defined? Surely that has to be passed in as a parameter to `do_something` or some other how? – NeilG Dec 02 '22 at 11:39
  • 1
    @NeilG the request object should be imported: `from flask import request` – Renato Byrro Dec 05 '22 at 12:01
  • Thanks @RenatoByrro, it often happens that partial examples exclude the imports and that can be frustrating when you're just looking to get started really quickly. Thanks for the update. – NeilG Dec 06 '22 at 11:15
0

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}")
Lambo
  • 1,094
  • 11
  • 18