0

Is there anyway to update with PUT method in flask restul with partially fields?

currently my PUT method perform this however if the fields it's not there gonna throw error.

item = ItemModel.find_by_id(id)
    item_json = request.get_json()

    if(item):
        item.name = item_json['name']
        item.code = item_json['code']
        item.tags = item_json['tags']
    else:
        try:
            item = item_schema.load(
                item_json
            )
         except ValidationError as err:
            return err.messages, HTTPStatus.BAD_REQUEST

    item.save_to_db()
    return {'message': item_schema.dump(item)}, HTTPStatus.OK
0

2 Answers 2

1

I found a way but not sure it's the best way or not. So the idea we make new function on model to update and pass JSON object and set attribute using the object.

from . import db


class ItemModel(db.Model):
    __tablename__ = "items"

    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(), nullable=False)
    name = db.Column(db.String(), nullable=False)
    tags = db.Column(db.String(), nullable=False)
    created_at = db.Column(db.DateTime, server_default=db.func.now())
    updated_at = db.Column(
        db.DateTime,
        server_default=db.func.now(),
        server_onupdate=db.func.now()
    )

    def update_to_db(self, data):
        for key, value in data.items():
            setattr(self, key, value)
        db.session.commit()

Now in resource we call the update function with input JSON from request.

@classmethod
def put(self, id: int):
    item = ItemModel.find_by_id(id)

    if(item):
        try:
            item.update_to_db(
                request.get_json()
            )
        except ValidationError as err:
            return err.messages, HTTPStatus.BAD_REQUEST

        return {'message': item_schema.dump(item)}, HTTPStatus.OK

    return {'message': gettext('item_not_found')}, HTTPStatus.NOT_FOUND

This is works but still not sure if there's any best way to do this.

0

Here's what I do:

  • Use a POST method to create a new item, and a PUT method to update an item.

  • Use the marshmallow Schema to validate the data first when the requests is received. You can use webargs for that. It is maintained by the marshmallow dev team. It throws the appropriate HTTP error (400 if the request is misformed and 422 if it is a correct json but fails validation).

  • There is no universal rule for the PUT. From a resource point of view, the PUT on an item is meant to replace the whole item (as opposed to a PATCH). This does not mean it is meant to replace the whole item in database, as there can be fields that are not modifiable by the user (the ID, created_at, updated_at, or some other fields that may be exposed in another resource, it really depends). The update_to_db method in your answer looks fine.

Note you still have to catch potential errors when writing to the database (database connexion error, item not found, integrity error (invalid foreign key),...) but at least the validation takes place as soon as possible.

2
  • have you try using ModelSchema instead? I want to use that so that validation like require=True can use from model by using nullable=False
    – Kevin
    Apr 4, 2019 at 8:10
  • I'm not that familiar with SQLAlchemy, and I didn't see all your code. Using marshmallow-sqlalchemy, I think you can generate the API schema from the model schema, in such a way that non-nullable model fields are marked as required.
    – Jérôme
    Apr 4, 2019 at 8:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.