4

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?

aesterisk_
  • 329
  • 4
  • 15

1 Answers1

3

I appreciate this is a little old but just had the same issue.

It looks like the "validate" actually sat over a python jsonschema impl, if you're still interested in digging, it's available here

That aside - you can configure restplus API to use a better formatchecker as follows: (I also validate date-time and date)

format_checker = FormatChecker(formats=["date-time", "email", "date"])
api_v1 = Api(
    app, version='1.4',
    title='[Anon]',
    description='[Anon] API for developers',
    format_checker=format_checker
)
Matt Harvey
  • 854
  • 8
  • 5