How to get POSTed json in Flask?

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the post with the PostMan Chrome extension, and the JSON I post is simply {"text":"lalala"}. I try to read the JSON using the following method:

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST']) def add_message(uuid):     content = request.json     print content     return uuid

On the browser it correctly returns the uuid I put in the GET, but on the console, it just prints out None (where I expect it to print out the {"text":"lalala"}. Does anybody know how I can get the posted JSON from within the Flask method?

回答1:

You need to set the request content type to application/json for the .json property to work; it'll be None otherwise. See the Flask Request documentation:

If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.

Flask 0.10 added the request.get_json() method, and you should use that method instead of the .json property. You can tell the method to skip the content type requirement by setting force=True.

Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.



回答2:

This is the way I would do it and it should be

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST']) def add_message(uuid):     content = request.get_json(silent=True)     print content     return uuid

With silent=True set, the get_json function will fail silently when trying to retrieve the json body. By default this is set to False. Setting force=True will ignore the request.headers.get('Content-Type') == 'application/json' check that flask does for you. By default this is also set to False. See flask documentation.

I would strongly recommend leaving force=False and make the client send the Content-Type header to make it more explicit.

Hope this helps!



回答3:

For reference, here's complete code for how to send json from a Python client:

import requests res = requests.post('http://localhost:5000/api/add_message/1234', json={"mytext":"lalala"}) if res.ok:     print res.json()

The "json=" input will automatically set the content-type, as discussed here: Post JSON using Python Requests

And the above client will work with this server-side code:

from flask import Flask, request, jsonify app = Flask(__name__)  @app.route('/api/add_message/<uuid>', methods=['GET', 'POST']) def add_message(uuid):     content = request.json     print content['mytext']     return jsonify({"uuid":uuid})  if __name__ == '__main__':     app.run(host= '0.0.0.0',debug=True)


回答4:

This solution works:

from flask import Flask, request, jsonify  app = Flask(__name__)   @app.route('/hello', methods=['POST']) def hello():    return jsonify(request.json)


转载请标明出处:How to get POSTed json in Flask?
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!