4

I'm facing a problem. I developed an API in Flask. I use python-requests to send POST requests (with dictionaries) to my API. Below, an example of how I sent requests.

import requests

data=dict()
data['a'] = "foo"
data['b'] = "bar"
data['ninja'] = {"Name": "John doe"}

r = requests.post("https://my_own_url.io/", data=data, headers={"content-type" : 'application/x-www-form-urlencoded'}, verify=False)

On the back-end of my flask application, I can received the request :

from flask import Flask, request

@app.route("/", methods=['POST'])
def home():
    content = request.form.to_dict()

if __name__ == "__main__":
    app.run()

Here is my problem, I send a python dictionary :

{'a' : "foo", 'b' : "bar", 'ninja':{'Name': "John Doe"}}

But I can only recover :

{'a' : "foo", 'b' : "bar", 'ninja':'Name'} Here ninja haven't the right value.

Do you know the right way to aim this ? :)

PicxyB
  • 596
  • 2
  • 8
  • 27
  • If you are using a POST request, use `request.args` instead. – coderman1234 Mar 22 '21 at 15:58
  • 1
    You can't send complex nested objects with `'application/x-www-form-urlencoded'` Consider using JSON or some similar format instead – mousetail Mar 22 '21 at 16:06
  • Well, it seems complicated. But how can I manage a json-like entry (dict, multidict ...) if I need to send a file (located in request.files) ? > 'application/json' doesn't allow file and 'application/x-www-form-urlencoded' doesn't allow complex nested objects. So you can't send both obkect in a single request ? – PicxyB Mar 22 '21 at 16:13

1 Answers1

3

You have to get the data on the server side (Flask app) as json, so you can use request.get_json() or request.json:

from flask import Flask, request

app = Flask(__name__)

@app.route("/", methods=['POST'])
def home():
    content = request.get_json()

if __name__ == "__main__":
    app.run()

Send it on the client side as:

import requests

data = dict()
data['a'] = "foo"
data['b'] = "bar"
data['ninja'] = { "Name": "John doe" }

r = requests.post("https://my_own_url.io/", json=data, verify=False)
Carlo Zanocco
  • 1,967
  • 4
  • 18
  • 31