Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Schema validation of mandatory fields on a blueprint with a HTTP PATCH method containing only modified fields #628

Open
juur opened this issue Mar 25, 2024 · 2 comments

Comments

@juur
Copy link
Contributor

juur commented Mar 25, 2024

I have a simple CRUD class (based on flask.views.MethodView).
The Schema class is based on marshmallow_sqlalchemy.SQLAlchemyAutoSchema.

 @_bp.arguments(AccountGroupModelSchema)
 @_bp.response(200, AccountGroupModelSchema)
 def patch(self, updated, account_group_id):
     """Update an existing object."""
     item = AccountGroup.query.get_or_404(account_group_id)

     item.name = updated.name or item.name

     db.session.commit()
     return item

When submitting a HTTP PATCH, the JSON payload contains only those fields being modified, e.g. { "name": "new_name" }. This means the Schema validation fails, because mandatory fields are not present.

Is there anyway to handle validating the fields that are present AND rejecting any fields that are unknown but NOT failing validation for missing (as not being modified) fields in a PATCH? Or do I just have to take the JSON directly, update the entity, then validate prior to updated in the ORM?

@juur
Copy link
Contributor Author

juur commented Mar 25, 2024

I figured it out, if i replace the decorator with this:

@_bp.arguments(AccountGroupModelSchema(partial=True))

the validate method ignores missing fields!

@juur juur closed this as completed Mar 25, 2024
@juur juur reopened this Mar 26, 2024
@juur
Copy link
Contributor Author

juur commented Mar 26, 2024

Whilst partial=True does permit PATCH to work with validation, it creates another problem within apispec causing errors like this to appear:

apispec/ext/marshmallow/openapi.py:135: UserWarning: Multiple schemas resolved to the name Account. The name has been modified. Either manually add each of the schemas with a different name or provide a custom schema_name_resolver.

I assume this is because apispec considers the partial Schema to be different to the non-partial one.
Therefore I'm back in the situation where just sending a single field in a PATCH doesn't work perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant