How to get POSTed JSON in Flask?

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

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

    @app.route('/api/add_message/', methods=['GET', 'POST'])
    def add_message(uuid):
        content = request.get_json(silent=True)
        # print(content) # Do your processing
        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. If you are always expecting a json body (not optionally), leave it as silent=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!

提交回复
热议问题