Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 252
user3582887 Avatar asked Jun 05 '15 18:06

user3582887


2 Answers

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
like image 81
davidism Avatar answered Oct 06 '22 12:10

davidism


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)
)
like image 22
kevswanberg Avatar answered Oct 06 '22 12:10

kevswanberg