- Flask Get Request Parameters (GET, POST and JSON)
- POST: Form/POST
- request.values: GET or POST
- request.json
- Combine request.form, request.args and request.json
- request.files
- request.method
- GET Request Query Parameters with Flask
- Get Query Parameters in Flask
- Check if Query Parameters are Not None
- Free eBook: Git Essentials
- Conclusion
- Get Query Parameters Using Flask
- Extract the Parameter With the Help of Request Query String in Flask
Flask Get Request Parameters (GET, POST and JSON)
NOTE: Return None if not available.
data = request.argsif 'name' in data: name = data['name']
NOTE: werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: ‘name’ exception when key not found
age = request.args.get('age', type=int)
NOTE: Will return None if age is not int .
POST: Form/POST
data = request.formdata['name']
age = request.form.get('age', type=int)
options = request.form.getlist('options')
request.values: GET or POST
Will get from both request.args or request.form .
name = request.values.get('name')
request.json
if request.is_json: name = request.json.get('name') age = request.json.get('age') # auto type casting depending on the json format
NOTE: request.json is None if this is not a valid json request
if request.is_json: data = request.get_json(force=True) if 'name' in data: name = data['name']
NOTE: 400 Bad Request is raised for request.get_json(force=True) when request is not json (on Development Server).
Combine request.form, request.args and request.json
from werkzeug.datastructures import CombinedMultiDictdata = CombinedMultiDict([request.values, request.json])if 'name' in data: name = data['name']
request.files
Uploaded files of FileStorage structure.
for param_name, fileinfo in request.files.items(): filename = fileinfo.filename mimetype = fileinfo.mimetype fileinfo.save('DESTINATION')
fileinfo = request.files['PARAM_NAME']
request.method
if request.is_json: . elif request.method == 'POST': . else request.method == 'GET': .
❤️ Is this article helpful?
Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.
Do send some 💖 to @d_luaz or share this article.
A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz
Travelopy — discover travel places in Malaysia, Singapore, Taiwan, Japan.
GET Request Query Parameters with Flask
Query Parameters are part of the Query String — a section of the URL that contains key-value pairs of parameters. Typically, parameters are sent alongside GET requests to further specify filters on the operation:
www.example.com/search?name=John&location=Miami
The parameters are defined after the ? character and each key-value pair is separated with a & . Spaces are represented as %20 and can also be represented as + . These map to a key-value set of:
It’s easy to manipulate the URL with JavaScript — so more often than not, query parameters are added as filters to searches. Additionally, by adjusting the content on the screen based on reproducible parameters, instead of the body of a request, results are shareable between users just by sending a link with the parameters!
For instance, on AirBnB — if you’re fully flexible on the location, dates and wish for an auto-suggest, a click of a button leads you to:
https://www.airbnb.com/s/homes?refinement_paths%5B%5D=%2Fhomes&date_picker_type=flexible_dates&search_mode=flex_destinations_search&search_type=AUTOSUGGEST
There are a few parameters here, such as refinement_paths , date_picker_type , search_mode , and search_type , each with a value.
In this short guide, we’ll take a look at how to get a GET Request’s Query Parameters in Flask.
Get Query Parameters in Flask
from flask import Flask, request # . @app.route('/search', methods=['GET']) def search(): args = request.args return args
The request.args field is an ImmutableMultiDict :
It can easily be converted into a regular dictionary via:
Additionally, you can search for a specific key in the dictionary via the get() method, returning an error if the key doesn’t match up to the preconceived argument list:
You can additionally cast the value to a different type, such as int or str while getting it. You can also set a default value if the value isn’t present already. For instance, a name parameter will probably be a string, but the price parameter might be an integer:
args.get("name", default="", type=str) args.get("price", default=0, type=int)
If you search for a non-existent key — a None is returned. This way, you can check whether a query parameter is missing, and act accordingly — assigning a default value or just not using it.
Let’s send a GET request to the endpoint with a name and location :
$ curl "localhost:5000/search?name=John&location=Miami"
Check if Query Parameters are Not None
When operating on parameters, you’ll typically want to check if they’re None and act accordingly. This can thankfully easily be done by getting an expected key and checking if it’s present in the dictionary!
Let’s create a mock database — just a dictionary of users and their locations. Then, based on the parameters passed in the URL, we’ll filter this dictionary and return the matching users that fit the criteria defined by the parameters:
from flask import Flask, request # . db_users = < "John" : "Miami", "David" : "Miami", "Jane" : "London", "Gabriella" : "Paris", "Tanaka" : "Tokyo" > @app.route('/search', methods=['GET']) def search(): args = request.args name = args.get('name') location = args.get('location') # result = db_users if None not in (name, location): result = for key, value in db_users.items() if key == name and value == location> elif name is not None: result = for key, value in db_users.items() if key == name> elif location is not None: result = for key, value in db_users.items() if value == location> return result
Here — we extract the name and location from the parameter list. If none are present — you may wish to return all of the users, or none at all. If you’d wish to return all of them — uncomment the result = db_users line.
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
If both the name and location are present, we filter the db_users by both parameters. If only one is present — we filter it only using the present parameter.
Now, if we send a GET Request with both or a single parameter, we’ll be greeted with:
$ curl "localhost:5000/search?name=John&location=Miami" $ curl "localhost:5000/search?name=John" $ curl "localhost:5000/search?location=Miami"
Two people are located in Miami, so just using the single search parameter nets us two users. There’s only one John in the dictionary, so only John is returned for the first two queries.
Conclusion
In this guide, we’ve taken a look at how to get the query parameters of an HTTP GET Request in Flask.
We’ve also taken a look at how to check whether the parameters are None and how to handle the lack thereof with a mock database.
Get Query Parameters Using Flask
We will learn, with this explanation, how to get the parameters from the URL with the help of the request query string in Flask.
Extract the Parameter With the Help of Request Query String in Flask
Generally, we build a clean URL with our parameters in Flask, but sometimes we want a traditional query string for whatever reason. Our query strings are easy to work with; they are just separated by & and the value on the right side.
Now we will show you exactly how to extract those, and we can use them somewhere in our application, so let’s get started. We will set up our Flask app, and we will import the Flask class from the Flask module, and we also need to import the request variable and instantiate an object with the Flask class.
from flask import Flask , request
We will define the main block, and inside this block, we will use the run() method to run our app. Then we will put debug equal to True .
if __name__=='__main__': app.run(debug=True)
Now we will create a new route and call params for this route, and the function will be named Get_Query_Params() . We will return some strings to get the parameters out of the query string.
We will need to use the requests variable, define two arguments and access the query parameter. To get them, we only need to call requests.args , a dictionary with all the parameters in the query string.
The first one will be called VAR1 , and the second one will be called VAR2 and store the dictionary values using the requests.args[‘key’] key. We are returning these dictionary items to display them on the page.
@app.route('/params') def Get_Query_Params(): VAR1=request.args['var1'] VAR2=request.args['var2'] return f'Student name is: VAR!> and Father nmae is: VAR2>'
Let’s start the server, pass the parameter inside the route, and hit Enter to see the parameter displayed.
Now we can see we easily extract these values from the query string.
We will take one more example to access all the query parameters. We will create a variable called var1 , which will store the request.args ; this is a dictionary containing all the keys and values we provide as our query parameters.
Now we will apply a for loop over the dictionary items and be able to access and print these keys and values.
@app.route('/') def Get_Query_Params(): var1=request.args for key,value in var1.items(): print(key,value)
Using the keys, we can also access specific query parameters using if-else statements to check those actual query parameters exist. For now, the way we use to access the key is using var1.get() instead of using request.args[‘key’] because get() is the method that helps us to access the key.
if 'nationality' in var1.keys(): print(var1.get('nationality')) return f'Age is var1.get("age")> and nationality is var1.get("nationality")>'
Now we save and start the server, go to the browser, and provide the key-value pair inside the route. When we run this page, then we can see the parameters displayed, as well as we can see in the console where keys and values are printed.
It is very similar to getting the data from a form; if someone submits a form, we can extract it from an endpoint.
from flask import Flask , request app = Flask(__name__) # @app.route('/params') # def Get_Query_Params(): # VAR1=request.args['var1'] # VAR2=request.args['var2'] # return f'Student name is: and Father nmae is: ' @app.route('/') def Get_Query_Params(): var1=request.args for key,value in var1.items(): print(key,value) if 'nationality' in var1.keys(): print(var1.get('nationality')) return f'Age is var1.get("age")> and nationality is var1.get("nationality")>' if __name__=='__main__': app.run(debug=True)
Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.