Because of project specificity I have to write my own model validator for Flask-restplus API app. Simply speaking - when validation error occurs, its format and status code (400) is not proper. It should return JSON object with messages in particular format with status code 422.
What I do is more or less this:
ns = api.namespace('somenamespace', description='blabla')
class MyModel(MyBaseModel):
def __init__(self):
self.id = fields.Integer()
self.name = fields.String()
my_model = api.model('MyModel', MyModel())
@api.marshal_list_with(my_model, envelope='json')
@ns.route('/')
class SomeClass(Resource):
@api.expect(my_model, validate=False)
@api.doc(responses={
200: 'Success',
401: 'Authentication Error',
403: 'Requested resource unavailable',
409: 'Conflict, document already exists',
422: 'Validation Error'
})
def post(self):
"""
Save single document in the database.
:return:
"""
request_payload = json.loads(request.data)
validated_payload, payload_errors = some_validation(request_payload)
if payload_errors:
return jsonify(payload_errors), 422
else:
return jsonify({'response': 'ok})
Instance of `MyModel` behaves basically like a dict, so no problem in registration. Problem is that when I send data in `-d`, be it through `curl` from command line, or swagger, I constantly get `400` instead of `422`. I assume this is due to the default, built-in validation of input data based on `MyModel`. This is cool, but I have to omit it, and apply my own validation.