How to get POSTed JSON in Flask?

前端 未结 10 1133
隐瞒了意图╮
隐瞒了意图╮ 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:59

    Try to use force parameter...

    request.get_json(force = True)

    0 讨论(0)
  • 2020-11-21 07:03

    The following codes can be used:

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

    Here is a screenshot of me getting the json data:

    You can see that what is returned is a dictionary type of data.

    0 讨论(0)
  • 2020-11-21 07:08

    Assuming that you have posted valid JSON,

    @app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
    def add_message(uuid):
        content = request.json
        print content['uuid']
        # Return data as JSON
        return jsonify(content)
    
    0 讨论(0)
  • 2020-11-21 07:11

    You may note that request.json or request.get_json() works only when the "Content-type: application/json" has been added in the header of the request. If you are unable to change the client request configuration, so you can get the body as json like this:

    data = json.loads(request.data)
    
    0 讨论(0)
提交回复
热议问题