How to get POSTed JSON in Flask?

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

    First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here.

    You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation:

    This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see is_json()), otherwise it will be None.

    You can tell request.get_json() to skip the content type requirement by passing it the force=True keyword argument.

    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.

提交回复
热议问题