Flask WTForms Accept Json (Including Array Field)

December 26, 2017

Install Flask-WTF.

pip install Flask-WTF

Create a WTForm.

from flask_wtf import FlaskForm
from wtforms import Field, StringField

class UserForm(FlaskForm):
    # disable csrf
    class Meta:
        csrf = False

    name = StringField()
    websites = ListField()

In order to accept a field which is an array, you need to create a custom field.

class ListField(Field):
    def process_formdata(self, valuelist):
        self.data = valuelist

Accept and return json request using flask-wtf.

from flask import jsonify, abort

class User:
    name = None
    websites = []

@app.route('/test_api', methods=['POST'])
def test_api():

    item = User()
    form = UserProfileForm(item=item)
    if form.validate():
        form.populate_obj(item)
    else:
        abort(401)

    return jsonify({'name': item.name, 'websites': item.websites})

User curl to test your json form api.

curl -H "Content-Type: application/json" -X POST -d '{"name":"xyz","websites":["https://html-color-codes.info/"]}' http://localhost/test_api
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.