Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample of Flask receiving JSON
# If /json route receives header "application/json"
@app.route("/json", methods=['GET','POST'])
def json():
app.logger.debug("JSON received...")
app.logger.debug(request.json)
if request.json:
mydata = request.json # will be
return "Thanks. Your age is %s" % mydata.get("age")
else:
return "no json received"
@Ddfulton

This comment has been minimized.

Copy link

@Ddfulton Ddfulton commented Dec 22, 2015

I copied this directly and I still get None for mydata in the browser. The app.debug.log, however, definitely receives the json.

@Adityamalik123

This comment has been minimized.

Copy link

@Adityamalik123 Adityamalik123 commented Jun 23, 2017

Ddfulton write {"age":"9"} in the body of JSON.. then it will display 9 instead of none

@ivansempijja

This comment has been minimized.

Copy link

@ivansempijja ivansempijja commented Dec 21, 2017

this might work better

mydata = request.get_json(force=True)

@ClimenteA

This comment has been minimized.

Copy link

@ClimenteA ClimenteA commented Mar 15, 2018

I don't know what I'm doing wrong here:
Javascript:
`var query = JSON.stringify({"City": "Iasi", "Option": "kebab"});

function post_query(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("In the if statement! status ok!");
document.getElementById("results").innerHTML = this.responseText;
};
};
xhttp.open("POST", "/listari", true);
xhttp.send(query);
console.log("query sent");
}

post_query(query)`

Flask:
@app.route('/listari', methods=['POST'])
def listings():
print('query arrived in /listari, ok!')
bin_data = request.stream.read()
mydata = request.get_json(force=True)
print('Here >>>',bin_data, type(bin_data))
return "Raspuns din flask: {}".format(bin_data)

Work randomly...Do you have any ideas?

@mre

This comment has been minimized.

Copy link

@mre mre commented Jan 15, 2019

Just in case people are having problems using this code, your request content type needs to be application/json. Otherwise you get None as the parsed value. https://stackoverflow.com/a/20001283/270334

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment