Flask WTForms Accept Json (Including Array Field)

Install Flask-WTF.

pip install Flask-WTF

Create a WTForm.

from flask_wtf import FlaskFormfrom wtforms import Field, StringFieldclass 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, abortclass 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

❤️ 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.