How to retrieve GET and POST parameters in Flask
Published on Aug. 22, 2023, 12:16 p.m.
To retrieve GET and POST parameters in Flask, you can use the request
object provided by Flask. Here are some examples:
GET parameters:
from flask import Flask, request
app = Flask(__name__)
@app.route('/get')
def get_parameter():
param = request.args.get('param_name')
# use param variable as needed
return "The parameter is: {}".format(param)
In this example, we define a route function called get_parameter
that retrieves a GET parameter called param_name
using request.args.get()
. We then use the retrieved parameter and return it as a string in the HTTP response.
POST parameters:
from flask import Flask, request
app = Flask(__name__)
@app.route('/post', methods=['POST'])
def post_parameter():
param = request.form.get('param_name')
# use param variable as needed
return "The parameter is: {}".format(param)
In this example, we define a route function called post_parameter
that retrieves a POST parameter called param_name
using request.form.get()
. We then use the retrieved parameter and return it as a string in the HTTP response.
Note that for POST parameters, you need to specify the allowed HTTP methods using the methods
keyword argument in the @app.route
decorator, as shown in the example above.