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

Custom Validation Error for @api.expect(validate=True) #731

Open
psdon opened this issue Oct 14, 2019 · 2 comments
Open

Custom Validation Error for @api.expect(validate=True) #731

psdon opened this issue Oct 14, 2019 · 2 comments
Labels

Comments

@psdon
Copy link

psdon commented Oct 14, 2019

Is there a way to create a custom validation error for @api.expect(validation=True)?

@api.route('/some-route')
class SomeResource(Resource):

    @api.expect(fields, validate=True)
    def post(self):
        pass

The default validation error I get when I post something illegal is something like this:

{
  "errors": {
    "field": "'field' is a required property"
  },
  "message": "Input payload validation failed"
}

I would like it to be customized to:

{
    "error": "Please input the field"
}
@psdon psdon added the bug label Oct 14, 2019
@knowBalpreet
Copy link

one way is to use the flask after_request method and do these changes there. just check if 'errors' field is present in the response, if it is there. modify it. Consider the following example:

 @app.after_request
  def after_request(response):
    if int(response.status_code) == 404:
      response.set_data(dumps({'success': False, 'data': [],
                               'msg': 'Resource not found. Check Resouce URI again'}))

    if int(response.status_code) >= 400:
      response_data = loads(response.get_data())
      if 'errors' in response_data:
        response_data = {"error": "Please input the field"}
        response.set_data(dumps(response_data))
      response.headers.add('Content-Type', 'application/json')
    return response

@peterjwest
Copy link

I could do with this, would you like to port this to flask-restx? Or do you mind if I do?

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

No branches or pull requests

3 participants