Updated April 20, 2023
Definition of Flask URL Parameters
Flask URL parameters is defined as a set of arguments in form of a query string that is passed to a web application through Flask. These parameters get bonded to the URL. When there is an URL that is built for a specific function using the url_for( ) function, we send the first argument as the function name followed by any number of keyword argument. Each of the keyword argument corresponds to a variable part of the URL. Any variable part in the url_for( ) function which is unknown argument are appended as query parameters to the URL. In this article we will understand the different utilities of URL parameters.
Syntax:
Now in this section we will go through some important syntax which enables us to perform the tasks in the list of utilities of URL parameters’ scope which are equally important as understanding the working of URL parameters in Flask.
- Access parameters in the URL by using GET method:
request.args.get('key')
- Retrieve query parameters from URL:
request.args['<argument name>']
- Adding variable sections to URL or Routing:
@app.route('/<end point>/<variable name>')
- Pass default parameters in the URL:
@app.route('/<end point>', defaults={'<variable name>' : '<default value>'})
How do URL Parameters Work in Flask?
Before we learn about the working of URL parameters it is important for us to know how URL is built and also where are URL parameters contained so that understanding about working gets clearer. As we already talked about URL building that it enables us to pass in arguments to the URL for using URL reversing functions. It is much better than hard coding in the templates. This may be because:
- Reversing technique is more descriptive than the URLs being hard-coded.
- In cases of modifying hard-coded URL manually, it requires a lot of documentation on where to change whereas, using reversing technique the URLs can be changed in one go.
- The Unicode data and the escape of special characters is handled transparently through URL building.
- The uncertainty of relative paths which has possibility of unexpected behavior is removed as here the generated paths are always absolute.
- In case of application being placed outside URL root, the url_for( ) functions effectively handles the exception.
Now that we know what it is in store in URL building let us start looking at how the URL query string looks like:
10.27.09.91/index?arg1=value1&arg2=value2
The above URL comprises of 2 parts, the URL address and the query string. Let us first talk about the query string and anything remaining apart from query string is URL address. The query string is the portion of the URL that starts with a question mark, following that are key value pairs which are separated by ampersand (&) and each key value pair is represented as key followed by an equal to sign (=) and then followed by the value. This type of string is quite frequently seen in various websites that passes an argument. The key in the query string is nothing but what we call as an argument and, in this section, we will learn various utilities revolving or concerning about arguments. Now anything else apart from the query string represent the URL address or the endpoint where we would be getting our output. The query strings we pass to the application enables us to pass data that doesn’t require user’s actions to be taken. A query string can be generated in the application and then appended to the URL so that the data is automatically passed when the user makes the request. For the matter of this article we talk about a specific query string to understand the working behind URL parameters through the 4 utilities we presented in the syntax section.
127.0.0.1/index?source=eduCBA&subject=urlParam
Now in order to retrieve the key from query, we have 2 ways, with both of them having some subtle differences. In the first one we would use request.args.get(‘<argument name>’) where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters. And finally, we need to replace <argument name> with the argument/variable we want the value of. This method works very well even if the query string doesn’t have the argument mentioned in the key.
The second method is by using request.args[‘<argument name>’]. Where only we don’t perform the GET operation, and for this case we might end up with a 400 error is the key mentioned is not present in the query string. Hence, the most recommended utility is to use the GET method to retrieve the value of the key.
Next 2 utilities are similar as well. Using the method, we can easily pass a variable name to the URL end point, thus making it dynamic in terms of the parameters passed. In the place where we don’t mention default, we might end up in an error, but using a single routing line of code in the other utility the problem can be tackled. In some cases, we might get an error when no argument is passed, and that is the reason of using a default argument. Through the utilities discussed above, we know in-depth about the utility and the working of URL parameter in Flask.
Examples of Flask URL Parameters
Following are the examples are given below:
Example #1
Access parameters in the URL by using GET method
Syntax:
from flask import Flask, request
appFlask = Flask(__name__)
@appFlask.route('/index')
def access_param():
source = request.args.get('source')
return '''<h1>The source value is: {}</h1>'''.format(source)
appFlask.run(debug=True, port=5000)
Output:
When the value is passed to source argument
When no value is passed to the argument
Example #2
Retrieve query parameters from URL:
Syntax
from flask import Flask, request
appFlask = Flask(__name__)
@appFlask.route('/index')
def access_param():
source = request.args['source']
return '''<h1>The source value is: {}</h1>'''.format(source)
appFlask.run(debug=True, port=5000)
Output:
When no value is passed to argument
When no value is passed to argument
Example #3
Adding variable sections to URL or Routing
Syntax:
from flask import Flask, url_for
appFlask = Flask(__name__)
@appFlask.route('/index/<subject>')
def subject(subject):
return 'The value is: ' + subject
appFlask.run(debug=True, port=5000)
Output:
When value is passed to “subject” argument
When no value is passed to “subject” argument
When some other key is passed as an argument
Example #4
Pass default parameters in the URL:
Syntax:
from flask import Flask, url_for
appFlask = Flask(__name__)
@appFlask.route('/index/', defaults={'subject' : 'Flask'})
@appFlask.route('/index/<subject>')
def subject(subject):
return 'The value is: ' + subject
appFlask.run(debug=True, port=5000)
Output:
When value is passed to “subject” argument
When no value is passed to the “subject” argument
When some other key is passed as an argument
Conclusion
In this article we have got an in-depth flavor of all utilities Flask URL parameters provide and with the examples discussed here, we complete the hands-on learning of Flask URL parameters. Rest is up to readers to experiment with the baseline discussed here and build their own app!
Recommended Articles
This is a guide to Flask URL Parameters. Here we also discuss the definition and how do url parameters work in flask? along with different examples and its code implementation. You may also have a look at the following articles to learn more –