Send JSON to Flask using requests

I am trying to send some JSON data to a Flask application using the requests library. I expect to get back application/json

from the server. This works fine when I use Postman, but when I use requests, I get application/html

back.

import requests
server_ip = 'server_ip:port/events'
headers = {'Content-Type': 'application/json'}
event_data = {'data_1': 75, 'data_2': -1, 'data_3': 47, 'data_4': 'SBY'}
server_return = requests.post(server_ip, headers=headers, data=event_data)
print server_return.headers
{'date': 'Fri, 05 Jun 2015 17:57:43 GMT', 'content-length': '192', 'content-type': 'text/html', 'server': 'Werkzeug/0.10.4 Python/2.7.3'}

      

Why is Flask not seeing JSON data and responding correctly?

+3


source to share


2 answers


You are currently not sending JSON data. You need to set the argument json

, not data

. In this case, you don't need to install content-type

.

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

      

The header text/html

you see is the content type of the response. The checkbox seems to be sending you HTML, which seems okay. If you are expecting to go application/json

back, it might be an error page returning since the JSON data was correctly submitted.



You can read json data in Flask with request.json

.

from flask import request

@app.route('/events', methods=['POST'])
def events():
    event_data = request.json

      

+13


source


I don't think the requests will automatically format the data in the headers. You will need to do this yourself.



import json
...

server_return = requests.post(server_ip, headers=headers, data = json.dumps(event_data))

      

+3


source







All Articles