'Flask - Detect when a POST parameter is not present

An endpoint of my server is triggered like this:

curl --header "Content-Type: application/json" --request POST --data '{"selected_object":"6qzEgPnzxZWW8MaSYwCquP.txt", "action": 0}' 0.0.0.0:5000/do_stuff

When the action parameter is given, it is parsed, and an operation is performed, depending on its value.

This is how it's parsed:

@app.route("/do_stuff", methods=["POST"])
def do_it():
    request_contents = request.get_json()
    what_action = request_contents.get("action")

I want to be able to make the server work, even when this is not available in the POST request.

How do i detect if the item action is available in the POST request?



Solution 1:[1]

Request.get_json() will return a dict. Just check if 'action' is in the dict.

action_exists = "action" in request_contents

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian