0

I've got this boilerplate code:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        text = request.get_json()
        return jsonify({'you sent:': text}), 201
    else:
        return jsonify({'about': 'hakuna matata'})

@app.route('/multi/<int:num>', methods=['GET'])
def get_multiply10(num):
    return jsonify({'result': num*10})

if __name__ == '__main__':
    app.run(debug=True)

when I jump into Python interpreter I can interact with the API with GET like this:

from requests import get, post

get('http://localhost:5000').json()

and it returns expected output, but when I try to execute POST request:

post('http://localhost:5000', data={'data': 'bombastic !'}).json()

I get returned None from the text variable, meaning POST request is being acknowledged but the data isn't making it through to the variable.

What am I doing wrong ?

mr_incredible
  • 837
  • 2
  • 8
  • 21
  • Do you get 201 in both cases? The POST should return 201 while the GET should return 200. – balderman Oct 24 '19 at 11:05
  • I'm getting 201 on POST and 200 on GET which is fine. – mr_incredible Oct 24 '19 at 11:07
  • OK. See https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request about the options you have to look for the data you post. I thin it is under `form` – balderman Oct 24 '19 at 11:10
  • 1
    Try `json` parameter instead: `requests.post('http://localhost:5000', json={'data': 'bombastic !'})` – m01010011 Oct 24 '19 at 11:10
  • @m01010011 That worked ! So when working with json (dictionary) data I need to use the `json` parameter and not `data` parameter. Feel free to post it as a solution and I'll tick it for you. – mr_incredible Oct 24 '19 at 11:15

1 Answers1

1

Apart from your case, many websites require JSON-encoded data. So, you'll have to encode it before posting:

r = requests.post(url, data=json.dumps(payload))

Alternatively, you can use the json parameter...

r = requests.post(url, json=payload)

... and let requests encode it for you.

m01010011
  • 895
  • 8
  • 13