python-restx / flask-restx

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
https://flask-restx.readthedocs.io/en/latest/
Other
2.14k stars 333 forks source link

is it possible to write a custom validation not in business code? #599

Open WilliamChen-luckbob opened 5 months ago

WilliamChen-luckbob commented 5 months ago

Hey there! I'm a newbie who just switched from Java to Python.

I've been looking into GPT and related documentation and issues. It seems that in the Flask-RESTx framework's API, if I want to implement custom input validation, I have to handle the specified parameters explicitly in the business code, and can't directly add a custom handler to the parser or model definition.

So, I have to create a separate code layer specifically for data validation, and I also need to write an additional set of Marshmallow data classes for further data validation.

I'm wondering if Flask-RESTx supports providing a validator superclass, which developers can then customize to implement their own classes and register them in Flask when initializing the Api object to achieve custom validation of request parameters.

Also, I'm not sure if it's possible to add a field in flask_restx.namespace.Namespace.parser() and in the definition of the type in flask_restx.fields to specify the validation class to use, and then apply it to my own decorators or generic processing layer. image

If custom validators could be added at the indicated position in the picture, and attempted during framework validation, it would greatly enhance the aesthetics and convenience of the code.

Recently, I successfully implemented custom validation by subclassing Namespace, RequestParser, and related models, and integrated it into Flask-Restx to perform an all-in-one validation. However, I still need to call parse_args() to validate the arguments. I believe that parse_args() is not necessary; it could be handled by the framework together with model validation in the validate_payload method of resource.py in Flask-RESTx, instead of manually writing it everywhere!