0

I am trying to send data from a python script to flask endpoint. I have tried many things but I don't understand where I am going wrong. Please let me know if you have a solution or any reference that can help me.

Thanks in advance

This is the Flask code which gets json data:

@app.route('/ramp-DynDB-DQ-PostTableItem', methods=['POST' , 'GET'])
def PostDQTableItem():
    data = request.get_json()
    print(data)

This is the Python Script that Posts data:

 import requests

newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = requests.post('http://blabla:5000/ramp-DynDB-DQ-PostTableItem',
                        data={"Key": "key", "Path": "path"},
                        headers=newHeaders)

Status code:

400
7
  • Your client code does not post any JSON. Commented Oct 22, 2020 at 14:04
  • correct me if I am wrong , I am guessing this is the JSON data={"Key": "key", "Path": "path"} Commented Oct 22, 2020 at 14:11
  • No, it's not. It's a regular Python dict. And requests will take that dict and transform it into the standard format for HTTP POSTs, which looks like this: Key=key&Path=path. You have two options: a) Change your client code so that it sends JSON. b) Change your server code so that it also accepts standard POST requests. Commented Oct 22, 2020 at 14:20
  • Can You give me example brother, I am okay to change both client or server code Commented Oct 22, 2020 at 14:25
  • There are many examples, have a look around. The standard format for HTTP POST requests is called application/x-www-form-urlencoded, the JSON format is called application/json. With these keywords you should find plenty of examples for both flask and requests. Commented Oct 22, 2020 at 14:45

1 Answer 1

1

Converting Dict to JSON format worked for me:

import requests, json

data = {"Key": "key", 
        "Path": "path"
        }

json_object = json.dumps(data, indent = 4)   
print(json_object) 
newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}
res = requests.get('http://blabla/ramp-DynDB-DQ-PostTableItem')
response = requests.post('http://blabla/ramp-DynDB-DQ-PostTableItem',
                        data=json_object,
                        headers=newHeaders)
print(response.text)
Sign up to request clarification or add additional context in comments.

2 Comments

You don't need to do all that requests has a json attribute: requests.post('http://blahblah/etc', json=data) would do the same as the above code. requests.readthedocs.io/en/master/user/quickstart/…
I tried that Doobeh, for some reason it said json is not recognized

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.