Send JSON to Flask using requests
Solution 1
You are not sending JSON data currently. You need to set the json
argument, not data
. It's unnecessary to set content-type
yourself in this case.
r = requests.post(url, json=event_data)
The text/html
header you are seeing is the response's content type. Flask seems to be sending some HTML back to you, which seems normal. If you expect application/json
back, perhaps this is an error page being returned since you weren't sending the JSON data correctly.
You can read json data in Flask by using request.json
.
from flask import request
@app.route('/events', methods=['POST'])
def events():
event_data = request.json
Solution 2
If you use the data
argument instead of the json
argument, Requests will not know to encode the data as application/json
. You can use json.dumps
to do that.
import json
server_return = requests.post(
server_ip,
headers=headers,
data=json.dumps(event_data)
)
user3582887
I enjoy writing code. I learned what I know through trial and error and the help of others here on Stack Overflow. I like Python the most of all the languages I have experienced. I also write some javascript, php, html. I have done a couple API's. One in PHP and one in Python using Flask.
Updated on July 22, 2022Comments
-
user3582887 almost 2 years
I am trying to send some JSON data to a Flask app using the requests library. I expect to get
application/json
back from the server. This works fine when I use Postman, but when I use requests I getapplication/html
back instead.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 isn't Flask seeing the JSON data and responding correctly?