Query Parameters with Multi-Value in Flask A
Python-based Flask is a micro-framework. It is well-known for creating RESTful APIs since it is lightweight and simple to use. We'll examine how to use multi-value query parameters with flask in this tutorial.
Let's learn basis with following example:
#app.py
from flask import Flask #import library
app = Flask(__name__) #init Flask app
@app.route('/')?
def home():
?return "Hello world"
?
if __name__ == '__main__':
??app.run(host='0.0.0.0', port=5000, debug=True)
To test our app We have to visit below url with the help of web brower:
https://127.0.0.1:5000
This shows "Hello world" text in the browser:
To get the query parameters in the URL in Flask, use request.args. In order to access and control the query parameters, we can use methods like get, getlist, and to_dict. The request.args property is a dictionary that maps the parameter names to their values. It should be noted that the request.args attribute only works for query parameters and not for URL path parameters.
#app.py
from flask import Flask #import library
app = Flask(__name__) #init Flask app
@app.route('/')?
def home():
?query = request.args.getlist('name')
??print(query)
??return f'Looking for: {query}'
?
if __name__ == '__main__':
??app.run(host='0.0.0.0', port=5000, debug=True)
If we have a url like this:
https://127.0.0.1:5000/?name=samrat&name=rocky
Output will be:
When a query string has multiple-valued arguments, for example:
In that case, request.args.to_dict() returned value is:
Even the name query parameters have many values, yet only one value is returned. the default assumption made by Flask is that query parameters have a single value. To return all values for each parameter as a list, we can add flat=False to the to_dict() function.
@app.route('/')
def home():
??query = request.args.to_dict(flat=False)
??print(query)
??return f'Looking for: {query}'
The result of this will be as follows:
Currently, lists are used to represent all multi-value query parameters