How do you access the query string in Flask routes?
Asked Answered
H

13

647

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 example.com/data?abc=123, I would like access to the string ?abc=123 or to be able to retrieve the value of parameters like abc.

@app.route("/data")
def data():
    # query_string = ???
    return render_template("data.html")
Hightoned answered 2/8, 2012 at 9:4 Comment(1)
If you want to receive this string you should use a sqlite or a mysql query. create a variable call "query_string" and use flask to mitage it with other functions and variables. While using Flask you can edit your "query_strings" highly and put them with other self made tags and imports. I hope this helped!Amateur
S
1166
from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')
Socrates answered 2/8, 2012 at 9:14 Comment(9)
This example returns that value of the "user" parameter passed in the query string, not the query string itself. "Query string" means everything after the question mark and before the pound sign, if one is present.Horseshit
still is a useful answer consider that it is related to the question. So valid and +1Autotrophic
Will this raise an exception if user is not present? (I guess not if args is just a dict.)Tirzah
No - as with a dict and .get, you'd just get None.Logion
@LyndsySimon: Well spotted. But since this answer correctly answers the question my Google search terms alluded to ('flask get request parameter') I'm up-voting it anyhow. I'm a pedant too, but I'm chalking this up to web mysticism. 😉Hermeneutics
No argument from me! My comments on this question have been an ongoing source of SO points and overall karma. :) Happy hacking!Horseshit
@Autotrophic it's not useful if, like OP, you need the actual string.Magritte
I am using your suggestion, but I can not input a value with space like software solutions. How to achieve this? Thanks.Termless
This may happen when the query string is not url encoded. Please look at the server log for two cases Encoded URL will be "GET /data?user=krace%20kumar HTTP/1.1" 200" Unencoded URL will be "GET /data?user=krace kumar HTTP/1.1" HTTPStatus.BAD_REQUEST -Socrates
H
329

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

@app.route('/adhoc_test/')
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.

Horseshit answered 2/8, 2012 at 16:29 Comment(4)
Im not sure why the answer says ETA: Before you go further, you should ask yourself why you want the query string, because if your API has OAuth kind of authentication mechanism, I think you will need to read query params, (not quite sure if I'm correct this about Flask since I started learning Flask today!)Tasha
@HasinthaAbeykoon yes, but in that case, you should not need to ingest the entire querystring, you should know which keys you need to check, and request those keys specifically via request.args.get.Disruptive
For reference, a "compelling reason not to" can for example be server-side image maps, as those aren't key=value pairs.Ashurbanipal
Or if something like proxying a request to another route or app, you might just want to append the raw querystring to the new url.Thermoluminescent
K
25

I came here looking for the query string, not how to get values from the query string.

request.query_string returns the URL parameters as raw byte string (Ref 1).

Example of using request.query_string:

from flask import Flask, request

app = Flask(__name__)

@app.route('/data', methods=['GET'])
def get_query_string():
    return request.query_string

if __name__ == '__main__':
    app.run(debug=True)

Output:

query parameters in Flask route

References:

  1. Official API documentation on query_string
Kennet answered 20/3, 2019 at 0:46 Comment(0)
V
22

We can do this by using request.query_string.

Example:

Lets consider view.py

from my_script import get_url_params

@app.route('/web_url/', methods=('get', 'post'))
def get_url_params_index():
    return Response(get_url_params())

You also make it more modular by using Flask Blueprints - https://flask.palletsprojects.com/en/1.1.x/blueprints/

Lets consider first name is being passed as a part of query string /web_url/?first_name=john

## here is my_script.py

## import required flask packages
from flask import request
def get_url_params():
    ## you might further need to format the URL params through escape.    
    firstName = request.args.get('first_name') 
    return firstName
    

As you see this is just a small example - you can fetch multiple values + formate those and use it or pass it onto the template file.

Vacuva answered 29/5, 2015 at 5:26 Comment(0)
P
17

Werkzeug/Flask as already parsed everything for you. No need to do the same work again with urlparse:

from flask import request

@app.route('/')
@app.route('/data')
def data():
    query_string = request.query_string  ## There is it
    return render_template("data.html")

The full documentation for the request and response objects is in Werkzeug: http://werkzeug.pocoo.org/docs/wrappers/

Pierson answered 3/8, 2012 at 9:8 Comment(0)
U
12

Try like this for query string:

from flask import Flask, request

app = Flask(__name__)

@app.route('/parameters', methods=['GET'])
def query_strings():

    args1 = request.args['args1']
    args2 = request.args['args2']
    args3 = request.args['args3']

    return '''<h1>The Query String are...{}:{}:{}</h1>''' .format(args1,args2,args3)


if __name__ == '__main__':

    app.run(debug=True)

Output: enter image description here

Unparliamentary answered 25/4, 2019 at 11:35 Comment(2)
After many years it solved my issue. ThanksEudosia
Thankful watching my solution @DjangodevUnparliamentary
E
7

Every form of the query string retrievable from flask request object as described in O'Reilly Flask Web Devleopment:

From O'Reilly Flask Web Development, and as stated by Manan Gouhari earlier, first you need to import request:

from flask import request

request is an object exposed by Flask as a context variable named (you guessed it) request. As its name suggests, it contains all the information that the client included in the HTTP request. This object has many attributes and methods that you can retrieve and call, respectively.

You have quite a few request attributes which contain the query string from which to choose. Here I will list every attribute that contains in any way the query string, as well as a description from the O'Reilly book of that attribute.

First there is args which is "a dictionary with all the arguments passed in the query string of the URL." So if you want the query string parsed into a dictionary, you'd do something like this:

from flask import request

@app.route('/'):
    queryStringDict = request.args

(As others have pointed out, you can also use .get('<arg_name>') to get a specific value from the dictionary)

Then, there is the form attribute, which does not contain the query string, but which is included in part of another attribute that does include the query string which I will list momentarily. First, though, form is "A dictionary with all the form fields submitted with the request." I say that to say this: there is another dictionary attribute available in the flask request object called values. values is "A dictionary that combines the values in form and args." Retrieving that would look something like this:

from flask import request

@app.route('/'):
    formFieldsAndQueryStringDict = request.values

(Again, use .get('<arg_name>') to get a specific item out of the dictionary)

Another option is query_string which is "The query string portion of the URL, as a raw binary value." Example of that:

from flask import request

@app.route('/'):
    queryStringRaw = request.query_string

Then as an added bonus there is full_path which is "The path and query string portions of the URL." Por ejemplo:

from flask import request

@app.route('/'):
    pathWithQueryString = request.full_path

And finally, url, "The complete URL requested by the client" (which includes the query string):

from flask import request

@app.route('/'):
    pathWithQueryString = request.url

Happy hacking :)

Eyeopener answered 25/4, 2020 at 3:49 Comment(0)
L
6

I prefer

user = request.args['user'] if 'user' in request.args else 'guest'

over

user = request.args.get('user')

this way, you can check the url actually contains the query string first

Lather answered 23/9, 2021 at 20:55 Comment(2)
Why not user = request.args.get('user', 'guest') ?Fotheringhay
Yep yours is better! I'm not sure, I think my team is using an older version of flask when I tried it didn't work as expected..Lather
W
4

Often we just want to map the whole query string into an appropriate python data structure and take it from there. The appropriate structure is a multi-dictionary because keywords can repeat, for example we need to handle A=123&A=456&B=789. A multi-dictionary is a list of 2-tuples where each 2-tuple contains the key as its first item and the list of values as its second, so the above goes to [('A',['123','456']),('B',['789'])]. All of this is achieved by

qstr = request.args.lists() # A generator for the multi-dict
qstr = list(qstr) # To get the actual multi-dict

If all you want is a dictionary where the first occurrence of a duplicate keyword is used you can just go

qstr = request.args.to_dict()
Washday answered 17/11, 2021 at 2:22 Comment(0)
L
3

The implementation below worked for me.

from flask import request
def getVerificationStatus():
try:
    requestId=int(request.args.get('requestId'))
    print(requestId)
    status= verificationStepRepository.getVerificationStatus(requestId)
    return tb.responsify(200, "success", status)
except Exception as e:
    return errorHandler.dispatchInternalServerError(str(e))
Loyola answered 14/4, 2021 at 19:19 Comment(0)
P
2

If the request if GET and we passed some query parameters then,

fro`enter code here`m flask import request
@app.route('/')
@app.route('/data')
def data():
   if request.method == 'GET':
      # Get the parameters by key
      arg1 = request.args.get('arg1')
      arg2 = request.args.get('arg2')
      # Generate the query string
      query_string="?arg1={0}&arg2={1}".format(arg1, arg2)
      return render_template("data.html", query_string=query_string)
Pneumonoultramicroscopicsilicovolcanoconiosis answered 15/2, 2020 at 18:35 Comment(1)
You may wish to fix the glaring typo in your first line.Disruptive
U
1

This can be done using request.args.get(). For example if your query string has a field date, it can be accessed using

date = request.args.get('date')

Don't forget to add "request" to list of imports from flask, i.e.

from flask import request
Unavailing answered 10/1, 2019 at 8:43 Comment(0)
S
1

This Code worked for me:

from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def search():
   query = request.args
   for key,value in query.items():
      print(key,value)
    return "Hello World"

if __name__ == '__main__':
  app.run(debug=True)
Sallie answered 29/12, 2022 at 8:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.