Use WTForms for RESTful Api Validation on Google Cloud Functions (Python)

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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.