0

I am getting error 400 BAD REQUEST when I try to send patch data

Below is the ajax code that we use for PATCH I use a function called getQueryVariable to extract an ID field from the URL

<script type = "text/javascript">
    $(function inputData() {

    $('#basic_update').click(function(e) {
        var cownumber = getQueryVariable("cownumber")
        var basic = {
            cownumber : $('#cownumber').val(),
            height: $('#height').val(),
            weight : $('#weight').val(),
            eartag : $('#eartag').val(),
            eid : $('#eid').val(),
            sex : $('#sex option:selected').text(),
            pasturenumber : $('#pasturenumber option:selected').text(),
            breed : $('#breed').val(),
            status : $('#status option:selected').text(),
            trial : $('#trial option:selected').text(),
            herd : $('#herd').val(),
            animaltype : $('#animaltype option:selected').text()
            }
            $.ajax({
                url: '/api/master_animal/'+cownumber,
                data: basic,
                datatype: 'json',
                type: 'PATCH',
                success: function(response) {
                    console.log(response);
                    alert("Data saved")
                },
                error: function(error) {
                    console.log(error)
                    alert("This cow number already exist");
                }
            });
            e.preventDefault();
        });
    });
</script>

I was not sure how to deal with not knowing exactly which variable will be changed so I thought it would be best to capture all the variables on the page (Is this the wrong idea?)

I have it using the URL /api/master_animal/cownumber

api = Api(app)
api.add_resource(table_basics, '/api/master_animal/<cownumber>')
api.add_resource(table_basics, '/api/master_animal/', endpoint = "cownumber")

In the views.py I have GET POST AND PATCH

class table_basics(Resource):

    def get(self, cownumber):
        master_animal_query = Master_animal.query.get_or_404(cownumber)
        #Serialize the query results in the JSON API format
        result = schemaMaster.dump(master_animal_query).data
        return result

    def post(self):
        raw_dict = request.get_json(force=True)
        master_dict = raw_dict['data']['attributes']
        try:
                #Validate the data or raise a Validation error if
                schemaMaster.validate(master_dict)
                #Create a master object with the API data recieved
                master = Master_animal(cownumber=master_dict['cownumber'], weight=master_dict['weight'],height=master_dict['height'],eartag=master_dict['eartag'],eid=master_dict['eid'],sex=master_dict['sex'],pasturenumber=master_dict['pasturenumber'],breed=master_dict['breed'],status=master_dict['status'],trial=master_dict['trial'],herd=master_dict['herd'],animaltype=master_dict['animaltype'])
                master.add(master)
                query = Master_animal.query.all()
                results = schemaMaster.dump(query, many = True).data
                return results, 201


        except ValidationError as err:
                resp = jsonify({"error": err.messages})
                resp.status_code = 403
                return resp               

        except SQLAlchemyError as e:
                db.session.rollback()
                resp = jsonify({"error": str(e)})
                resp.status_code = 403
                return resp

    def patch(self, cownumber):
        master_animal_query = Master_animal.query.get_or_404(cownumber)
        raw_dict = request.get_json(force=True)
        master_dict = raw_dict['data']['attributes']
        try:
            schemaMaster.validate(master_dict)
            for key, value in master_dict.items():
                setattr(master_animal_query, key, value)

            master_animal_query.update()
            return self.get(cownumber)

        except ValidationError as err:
            resp = jsonify({"error": err.messages})
            resp.status_code = 401
            return resp

        except SQLAlchemyError as e:
            db.session.rollback()
            resp = jsonify({"error": str(e)})
            resp.status_code = 401
            return resp

I have used Postman/Curl to verify that I can use the patch command at api/master_animal/, so I know the functionality works but whenever I run the ajax code, I get the error bad request

0 Answers0