Edit requirements.txt
# https://pypi.org/project/WTForms/
WTForms==2.2.1
Create WTForms
from wtforms import Form, BooleanField, StringField, validatorsclass RequestInviteForm(Form): email = StringField('Email', [validators.Length(min=6, max=120), validators.Email()]) # email = StringField('Email', [validators.Email()])
Abort for json request.
from flask import jsonify, abort# https://cloud.google.com/apis/design/errors#http_mappingdef json_abort(status_code, message, details=None): data = { 'error': { 'code': status_code, 'message': message } } if details: data['error']['details'] = details response = jsonify(data) response.status_code = status_code abort(response)
Code
from flask import jsonifyfrom werkzeug.datastructures import ImmutableMultiDictdef request_invite(request): ''' data = request.json.get('data') if 'email' not in data: json_abort(400, message="Missing email") ''' if not request.is_json: json_abort(400, 'JSON request expected') form = RequestInviteForm(ImmutableMultiDict(request.json.get('data'))) if not form.validate(): json_abort(400, 'validation error', details=form.errors) email = form.email.data # so something return jsonify({ 'data': { 'email': email } })
References: