How do you access the query string in Flask routes?


How do you access query parameters or the query string in Flask routes? It"s not obvious from the Flask documentation.

The example route /data below illustrates the context that I would like to access that data. If someone requests something like, I would like access to the string ?abc=123 or to be able to retrieve the value of parameters like abc.

def data():
    # query_string = ???
    return render_template("data.html")

Answer rating: 976

from flask import request

def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get("user")

Answer rating: 291

The full URL is available as request.url, and the query string is available as request.query_string.decode().

Here"s an example:

from flask import request

def adhoc_test():

    return request.query_string

To access an individual known param passed in the query string, you can use request.args.get("param"). This is the "right" way to do it, as far as I know.

ETA: Before you go further, you should ask yourself why you want the query string. I"ve never had to pull in the raw string - Flask has mechanisms for accessing it in an abstracted way. You should use those unless you have a compelling reason not to.

Get Solution for free from DataCamp guru