Flask - Get keys and values from URL using request.args

by
Jeremy Canfield |
Updated: May 05 2025
| Flask articles
Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.
- Model -> models.py
- View -> views.py
- Controller -> __init__.py
Let's say your flask project has the following structure.
├── main.py
├── my-project (directory)
│ ├── __init__.py
│ ├── views.py
│ ├── templates (directory)
│ │ ├── base.html
│ │ ├── home.html
│ │ ├── test.html
Let's say a request is submitted to the /Test route of your Flask application with the following parameters.
http://www.example.com/Test?foo=Hello&bar=World
request.headers can be used to return full path.
request.args.get can be used to get the values (Hello and World) from the keys (foo and bar).
In your view (views.py in this example), here is how you could print the values to your terminal console.
#!/usr/bin/python3
from flask import request
@views.route('/Test', methods=['GET', 'POST'])
def test():
print(f"request.full_path = {request.full_path}") # <- /Test?foo=Hello&bar=World
print(f"foo = {request.args.get('foo')}") # <- Hello
print(f"bar = {request.args.get('bar')}") # <- World
return render_template('test.html')
Here is how you can determine if a request.args key exists.
#!/usr/bin/python3
from flask import request
@views.route('/Test', methods=['GET', 'POST'])
def test():
if 'foo' in request.args:
print(request.args.get('foo'))
if 'bar' in request.args:
print(request.args.get('bar'))
return render_template('test.html')
Here is an example with error handling.
#!/usr/bin/python3
from flask import request
@views.route('/Test', methods=['GET', 'POST'])
def test():
try:
request.full_path
except KeyError:
print(f"request.full_path raised KeyError")
pass
try:
request.args.get('foo')
except KeyError:
print(f"got KeyError - there is no foo URL parameter")
pass
example NameError:
print(f"got NameError - the foo URL parameter contains no value")
pass
else:
print(f"foo = {request.args.get('foo')}")
return render_template('test.html')
Did you find this article helpful?
If so, consider buying me a coffee over at