How to receive form data from Jotform with Python and Flask

257 Views Asked by At

Jotform is a great service to easily create online forms in minutes. Sometimes you may need to analyze the data that has been sent. You can ask Jotform to send you the data collected via webhook whenever a user submits a form. The problem is that in the jotform documentation there are only examples for the PHP language.

On the other hand, I need to get that data in Python with Flask...

1

There are 1 best solutions below

0
Cesco On

I wrote this little piece of code to receive and process the data from Jotform with Python 3.6+ and Flask. It will work with the majority of fields, I'm not sure about file and multimedia fields since I've not yet tested them. Please feel free to use it, if it can help you too.

import json
from flask import Flask, request


app = Flask(__name__)


def extract_jotform_data():
    output = {}
    form_data = request.form.to_dict()
    if form_data.get("rawRequest"):
        for key, value in json.loads(form_data["rawRequest"]).items():
            # Removes the "q<number>_" part from the key name
            # Instead of "q5_quantity" we want "quantity" as the key
            temp = key.split("_")
            new_key = key if len(temp) == 1 else "_".join(temp[1:])
            # Saves the item with the new key in the dictionary
            output[new_key] = value

    return output


@app.route('/', methods=['GET', 'POST'])
def hello_world():
    jotform = extract_jotform_data()
    for key, value in jotform.items():
        print(f"{key}: {value}")
        if type(value) is dict:
            for subkey, subvalue in value.items():
                print(f" +------ {subkey}: {subvalue}")

    return "ok", 200


if __name__ == '__main__':
    app.run()