Flask Get Request Parameters (GET, POST and JSON)

May 29, 2019
from flask import request

request.args: Query parameters/GET

name = request.args.get('name')

NOTE: Return None if not available.

data = request.argsif 'name' in data:    name = data['name']

NOTE: werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'name' exception when key not found

Cast Parameter Type

age = request.args.get('age', type=int)

NOTE: Will return None if age is not int.

POST: Form/POST

name = request.form.get('name')
data = request.formdata['name']
age = request.form.get('age', type=int)

List of values

options = request.form.getlist('options')

request.values: GET or POST

Will get from both request.args or request.form.

name = request.values.get('name')

request.json

if request.is_json:    name = request.json.get('name')    age = request.json.get('age') # auto type casting depending on the json format

NOTE: request.json is None if this is not a valid json request

if request.is_json:    data = request.get_json(force=True)    if 'name' in data:        name = data['name']

NOTE: 400 Bad Request is raised for request.get_json(force=True) when request is not json (on Development Server).

Combine request.form, request.args and request.json

from werkzeug.datastructures import CombinedMultiDictdata = CombinedMultiDict([request.values, request.json])if 'name' in data:    name = data['name']

request.files

Uploaded files of FileStorage structure.

for param_name, fileinfo in request.files.items():    filename = fileinfo.filename    mimetype = fileinfo.mimetype    fileinfo.save('DESTINATION')
fileinfo = request.files['PARAM_NAME']

request.method

if request.is_json:    ...elif request.method == 'POST':    ...else request.method == 'GET':    ...

References:

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