Search code examples
pythonpython-3.xmarshmallow

Marshmallow - how to use loaded data in validation


I am creating an API using marshmallow for the data validation.

the data is given to the schema in JSON:

data = request.get_json()
schema = ItemSchema()
evaluated = schema.load(data)

if evaluated.errors:
            return {'message': evaluated.errors}, 400

The schema has field validation methods which are decorated with the @validates decorator:

@validates('name')
def validate_name(self, name):
    existing_item = ItemModel.name_exists(name) #returns an object of type Item if the name exists. Names are unique
    if existing_item and existing_item._id !=  data['_id']:
        raise ValidationError('Item already exists.')

As in this example i would like to access the data dictionary which is passed via the load function. How can i access the data object inside the validation method of the schema?

Thanks for your help!


Solution

  • To answer your question, you can use a schema validator with the @validates_schema decorator. It has a pass_original parameter.

    @validates_schema(pass_original=True)
    def validate_name(self, data, input_data):
        existing_item = ItemModel.name_exists(data['name'])
        if existing_item and existing_item._id !=  input_data['_id']:
            raise ValidationError('Item already exists.')
    

    But frankly, I think your use case is wrong.

    If it is an item creation (POST), just check whether the name already exists.

    If it is an item modification (PUT), you know the ID from the request path. And you should be able to access it from your object.

    Also, if I may suggest, you could use webargs (maintained by marshmallow maintainers) to parse request with marshmallow easily.