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

June 2, 2019

Edit requirements.txt

# https://pypi.org/project/WTForms/
WTForms==2.2.1

Create WTForms

from wtforms import Form, BooleanField, StringField, validators

class 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_mapping
def 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 jsonify
from werkzeug.datastructures import ImmutableMultiDict

def 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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.