user3582887
user3582887

Reputation: 413

Send JSON to Flask using requests

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 get application/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?

Upvotes: 10

Views: 21838

Answers (2)

kevswanberg
kevswanberg

Reputation: 2109

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)
)

Upvotes: 3

davidism
davidism

Reputation: 127180

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

Upvotes: 23

Related Questions