Get the form fields | JSON data in Python Flask

How to get the form fields in Flask | JSON data in Python Flask?

In the flask, you can receive form fields using the request object. The request object has a form attribute that contains all the data submitted via the form.

To access a specific form field, you can use the get() method of the request object. For example, to get the value of the “username” field, you would use request.form.get('username')

In order to receive the data in Python Flask, you need to import the request module.

from flask import request

How to get URL query parameters?

The variable names in query parameters are simple to manipulate in Flask. You may get the data with the help of request.args.get().

name = request.args.get("name")
age = request.args.get("age")

How to get the form fields in the flask?

If you want to get the data from the input fields of a form then you can get the data using the request.form.get().

name = request.form.get('name')
age = request.form.get('age')

Alternatively, you can use the indexing method. Specify the names of an input field if you know the key exists.

name = request.form['name']
age = request.form['age']

How to get the JSON Data?

To get the JSON with the content-type application/json, use request.get_json() in Flask.

Flask returns None if the content type is incorrect. Also, you will get an error if the data is not in JSON format.

data = request.get_json()

Add comment