EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Flask Tutorial Flask URL Parameters
Secondary Sidebar
Flask Tutorial
  • Flask
    • Flask Version
    • Flask make_response
    • Flask WebSocket
    • Flask Session
    • Flask Environment Variables
    • Flask Cache
    • Flask Server
    • Flask jsonify
    • Flask logging
    • Flask redirect
    • Flask wtforms
    • Flask config
    • Flask Users
    • Flask upload file
    • Flask? get post data
    • Flask Template
    • Flask DB Migrate
    • Flask HTTPS
    • Flask bcrypt
    • Flask debug mode
    • Flask authentication
    • Flask Migrate
    • Flask URL Parameters
    • Flask API
    • Flask bootstrap
    • Flask POST request
    • Flask Extensions

Flask URL Parameters

By Priya PedamkarPriya Pedamkar

Flask URL Parameters

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')

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Retrieve query parameters from URL:

request.args['<argument name>']

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,502 ratings)
  • 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

Flask URL Parameters-1.1

When no value is passed to the argument

 Flask URL Parameters-1.2

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

Flask URL Parameters-1.3

When no value is passed to argument

Output-1.4

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

Flask URL Parameters-1.5

When no value is passed to “subject” argument

Output-1.6

When some other key is passed as an argument

 Output-1.7

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

Output-1.8

 

When no value is passed to the “subject” argument

Output-1.9

When some other key is passed as an argument

Output-1.10

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 –

  1. Django vs Flask
  2. Docker Stack
  3. Python Rest Server
  4. Python Frameworks
Popular Course in this category
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)
  41 Online Courses |  13 Hands-on Projects |  322+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more