I'm trying to create a custom field for validating POSTed JSON in my API using Flask-RESTPlus 0.10.1
Below is the basic setup...
from flask_restplus import fields
import re
EMAIL_REGEX = re.compile(r'\S+@\S+\.\S+')
class Email(fields.String):
__schema_type__ = 'string'
__schema_format__ = 'email'
__schema_example__ = 'email@domain.com'
def validate(self, value):
if not value:
return False if self.required else True
if not EMAIL_REGEX.match(value):
return False
return True
I like the way the above documents in Swagger UI, but I can't seem to figure out how to actually use the validate method on it.
Here's how I'm using the custom field.
Json = api.model('Input JSON', {
'subscribers': fields.List(Email),
[...]
})
@api.expect(Json) // validate is globally set to true
def post(self):
pass
I've had luck using
'subscribers': fields.List(fields.String(pattern='\S+@\S+\.\S+'))
instead, but this doesn't give me the control to customize the error message, where'd I'd like it to return that the field is not of the email type.
I've also gone on and added a custom validate_payload
function (found within http://aviaryan.in/blog/gsoc/restplus-validation-custom-fields.html) that I call again within my POST method (instead of api.expect
). This requires me to duplicate some core functionality and call it every time in addition to api.expect
to output the proper Swagger documentation and a little bit of finesse to get it to work within nested fields.
It's my understanding that this should work out of box? Am I wrong? What am I missing here?