How to Obtain Values of Request Variables in Flask
Last Updated :
24 Apr, 2025
In this article, we will see how to request the query arguments of the URL and how to request the incoming form data from the user into the flask.
In a flask, to deal with query strings or form data, we use Request variables.
For example, a query string may look like this:
google.com/search?q=python
Let's start by creating a demo flask project. To be able to request data we will need to import the request from the Flask library.
Python3
# importing Flask and request
# from the flask library
from flask import Flask, request, render_template # to render html code
# pass current module (__name__)
# as argument to create instance of flask app
app = Flask(__name__)
# ‘/search’ URL is bound with search() function.
@app.route('/search') # for requesting query arguments
# defining a function search which returns the rendered html code
def search():
return render_template("search.html")
# ‘/name’ URL is bound with name() function.
@app.route('/name') # for requesting form data
# defining a function name which returns the rendered html code
def name():
return render_template("name.html")
# for running the app
if __name__ == "__main__":
app.run(debug=True)
The route() function of the Flask class is a decorator, which tells the application which URL should call the associated function.
Here we have created two routes /search to request query arguments and /name to request form data.
We will update them as we move ahead. Again details can be understood from here.
Requesting query arguments
As explained above a query string is the part after the question mark:
https://www.google.com/search?q=python
Here in our case the app, by default, runs on 127.0.0.1:5000 so suppose we add a query string to /search route for performing a search, it will look like this with key query and value g4g :
http://127.0.0.1:5000/search?query=g4g
Now we want to extract the value. For that we use request.args.get('query') or request.args['query'] .
It is recommended to use request.args.get('query') as the second will run into an 400 error if the query key is not provided.
So let's make changes to our /search route
Python3
@app.route('/search')
def search():
query = request.args.get('query')
# passing the value to html code
return render_template("search.html", query=query)
This will render this HTML code:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
</head>
<body>
<h2>You searched for {{query}}</h2>
<!-- {{query}} is the value returned from the search function -->
</body>
</html>
So after running the app and going to
http://127.0.0.1:5000/search?query=g4g
will give this output:
Requesting form data
Now if we are required to extract data from the POST method. Let's take a simple example by requesting the name and email of a user in a form:
Code for the above form:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Name</title>
</head>
<body>
<form action="/name" method="POST">
<label>Enter your name:</label>
<input type="text" name="name" required />
<br>
<label>Enter your email:</label>
<input type="text" name="email" required />
<input type="submit" value="Submit">
</form>
<br><br>
DATA RECEIVED:
<br>
{{name}}
<br>
{{email}}
</body>
</html>
So to request the name and email from the form we use request.form.get('name') and request.form.get('email') as the name of HTML has value name and email in the input tag:
<input type="text" name="name" required />
<input type="text" name="email" required />
Now let's see the Python code:
Here we require to give the methods we are using in the route. So when the form is submitted, the code from the POST method is executed, and if the method is GET the code from the else condition is executed.
Python3
# passing required methods
@app.route('/name', methods=['GET', 'POST'])
def name():
if request.method == 'POST':
# if form is submitted this code will be executed
name = request.form.get('name')
email = request.form.get('email')
return render_template("name.html", name=name, email=email)
else:
# if only visited
return render_template("name.html")
So now if the URL is visited and the data is entered on:
http://127.0.0.1:5000/name
This page looks like this:
and after submitting the form, the if condition is evaluated as true and the values are requested and returned back to the HTML code. The page now looks like this:
Instead of using request.form.get('email') we can also use request.form['email'] and results will be the same, the difference is the second one is returned in the form of a dictionary.
Summary
To request data of a query string we use:
request.args.get('query') //recommended or request.args['query']
To request data of a form we use:
request.form.get('name') //recommended or request.form['name']
Similar Reads
Using Request Args for a Variable URL in Flask
This article will teach us how to use Request Arguments in our Flask application. First, we will understand. What are the Request Arguments? What are the Request Arguments? Request Arguments are MultiDict objects with the parsed contents of the query string (the part in the URL after the question ma
4 min read
How to use variables and data files together in Postman ?
In this article, we are going to learn the process of using variables and data files together in the Postman. Postman is a powerful tool for API testing, offering extensive capabilities for automating tests and handling various API request types. One of its key features is the ability to use variabl
6 min read
How To Print A Variable's Name In Python
In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simp
3 min read
How To Process Incoming Request Data in Flask
In this article, we will learn how we can use the request object in a flask to process Incoming request data that is passed to your routes and How To Process incoming Request Data in Flask using Python. Flask has some functionality like tools, libraries, and technologies that allow you to build a we
4 min read
How to Access Dynamic Variable {{$guid}} inside Pre request in Postman?
During the testing stage in API development, it is important to extensively test the APIs to ensure they work without any problems in the production stage. We need a huge amount of test data for this purpose. Generating it manually can be a cumbersome and time-consuming task. Instead, we need some k
4 min read
What is the use of the $_REQUEST variable in PHP ?
Uses of PHP $_REQUEST: The PHP $_REQUEST is a PHP superglobal variable that is used to collect the data after submitting the HTML forms as the $_REQUEST variable is useful to read the data from the submitted HTML open forms.$_REQUEST is an associative array that by default contains contents of an $_
2 min read
Explain the use of environment variables in Postman requests.
Postman is a powerful API development tool which offers a feature known as environment variables. These variables are used for efficiently testing and development of APIs by allowing users to manage dynamic values across requests easily. Table of ContentWhat are Environment Variables in Postman?Adva
2 min read
How to Upload Files Using Python Requests Library
We are given some files and our task is to upload it using request library of Python. In this article, we're going to discover a way to use the requests library to add files in diverse scenarios, such as uploading unmarried documents, multiple files, and documents with extra form statistics Upload F
3 min read
How to get GET request values in Django?
Django, a high-level Python web framework, simplifies the process of web development. One common task in web applications is handling GET requests, which are typically used to retrieve data from a server. In this article, we'll create a small Django project that displays a message using data from a
2 min read
How to Store Username and Password in Flask
This article covers storing usernames and passwords in a Flask web app using MySQL. After logging in, users see a welcome message with their username.InstallationTo make our project we first create a virtual environment, to learn how to create and activate a virtual environment, refer to - Python vi
6 min read