GET Request Query Parameters with Flask

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:

name=John
location=Miami

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:

print(type(args))
# <class 'werkzeug.datastructures.ImmutableMultiDict'>

It can easily be converted into a regular dictionary via:

print(type(args.to_dict()))
# <class 'dict'>

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:

print(args.get("name"))
# John

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"

This results in:

{"location":"Miami","name":"John"}

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 = {key: value for key, value in db_users.items() if key == name and value == location}
    elif name is not None:
        result = {key: value for key, value in db_users.items() if key == name}
    elif location is not None:
        result = {key: value 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"
{"John":"Miami"}

$ curl "localhost:5000/search?name=John"
{"John":"Miami"}

$ curl "localhost:5000/search?location=Miami"
{"David":"Miami","John":"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.

Last Updated: December 9th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

Want a remote job?

    © 2013-2022 Stack Abuse. All rights reserved.

    DisclosurePrivacyTerms