How to get POSTed JSON in Flask?

前端 未结 10 1128
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 06:35

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 <

10条回答
  •  我在风中等你
    2020-11-21 06:49

    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/', 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)
    

提交回复
热议问题