Open In App

Access the Query String in Flask Routes

Last Updated : 06 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to Access the Query String in Flask Routes in Python. The query string is the portion of the URL and Query Parameters are part of the query string that contains the key-value pair.

Example:

http://127.0.0.1:50100/?name=isha&class=10

After ? character, everything is a query parameter separated by &. Here name=isha and class=10 are query parameters. 

In Flask, we can use the request.query_string attribute of the request object to access the raw query string in the URL. We can use it like this:

Python3




from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def search():
    query_string = request.query_string
    return f'Query string: {query_string}'
 
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=50100, debug=True)


This will return the following response:

Output1

We can use the request.args if we want to access the individual parameter keys and values which is a dictionary that maps the parameter names to their values. We can use it like this:

@app.route('')
def search():
    name = request.args.get('name')
    class = request.args.get('class')
    return Searching : name {name}, class {class}'

The output will look like this:

Output2

We can also use the request.args.getlist method to retrieve a list of values for a parameter, if the parameter has multiple values. 

For example:

Python




from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def search():
    query = request.args.getlist('name')
    return f'Name: {query}'
 
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=50100, debug=True)


The following will be its output:

Output3



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads