Open In App

Multi-value Query Parameters with Flask

Flask is a micro-framework written in Python. It is lightweight, and easy to use, making it famous for building RESTful APIs. In this article we are going to see how to use Multi-value query parameters with flask.

You can know more about it here.



Let’s understand the basics with an example:




from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
def search():
  return "Hello world"
 
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=50100, debug=True)

To test the app, we will open a web browser and navigate to 



http://127.0.0.1:50100/ 

This will display the “Hello world” message in the browser as shown in the figure.

Output1

In Flask, we can use the request.args to access the query parameters in the URL. The request.args attribute is a dictionary that maps the parameter names to their values so we can use methods like get, getlist, and to_dict to access and manipulate the query parameters. Note that the request.args attribute only works for query parameters, not for parameters in the URL path. 

Example:




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

For example, if we have a URL with the following query parameters:

http://127.0.0.1:50100/?name=isha&name=shaw

The output will be like this:

Output2

If the query string has multi-value parameters like this:

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

Then the value returned by request.args.to_dict() is

Output3

We can see that even name query parameters has multi-value but the value returned is single-value. Because Flask by default assumes query parameters to be of a single value. We can add flat=False into getdict() to return all values for each parameter as a list.

@app.route('/')
def search():
    query = request.args.to_dict(flat=False)
    print(query)
    return f'Searching for: {query}'

This will return the following response:

Output4

Now, all multi-value query parameters are represented by lists.


Article Tags :