How handle PATCH method in Flask route as API?

10,957

With PATCH requests you retrieve request data the same way you do for every other request type (e.g. POST). Depending on how you send your data, there are several ways to retrieve it:

Sending as application/json:

data = request.json

Sending as application/x-www-form-urlencoded (form data)

data = request.form

Sending as raw body with no Content-Type header:

data = request.data

The last one will give you a bytes string that you will then have to process accordingly. For your use case I suggest using the first example and add a Content-Type: application/json header when you send your PATCH request.

Share:
10,957
Chiefir
Author by

Chiefir

Python follower, Django enthusiast, coding fan.

Updated on July 25, 2022

Comments

  • Chiefir
    Chiefir almost 2 years

    I have this route:

    @bp.route('coordinates/<int:id>/update', methods=['PATCH'])
    def update_coordinates(id):
        schema = CoordinatesSchema()
        coords = Coordinates.query.get_or_404(id)
        new_data = request                           #????
    
        # some another logic
        return jsonify({"result": "GOOD"}), 200
    

    I am passing a data for update in a body, like a dict: { "title": "newtitle"} but I how can I get this info inside a route?

    • amanb
      amanb over 5 years
      You could try a Flask extension called Flask-Restless that implements this. A complete working example is available on the Flask-Restless documentation.