Flask App Routing - GeeksforGeeks

27 Oct, 2021
App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. 
Example: In our application, the URL (“/”) is associated with the root URL. So if our site’s domain was www.example.org and we want to add routing to “www.example.org/hello”, we would use “/hello”. 
To bind a function to an URL path we use the app.route decorator. In the below example, we have implemented the above routing in the flask.
main.py
from flask import Flask  app = Flask(__name__)  # Pass the required route to the decorator.@app.route("/hello")def hello():    return "Hello, Welcome to GeeksForGeeks"    @app.route("/")def index():    return "Homepage of GeeksForGeeks"  if __name__ == "__main__":    app.run(debug=True)
The hello function is now mapped with the “/hello” path and we get the output of the function rendered on the browser.
Step to run the application: Run the application using the following command.
python main.py
Output: Open the browser and visit 127.0.0.1:5000/hello, you will see the following output.
Dynamic URLs – We can also build dynamic URLs by using variables in the URL. To add variables to URLs, use <variable_name> rule. The function then receives the <variable_name> as keyword argument.
Example: Consider the following example to demonstrate the dynamic URLs.
main.py
from flask import Flask  app = Flask(__name__)  @app.route('/user/<username>')def show_user(username):    # Greet the user    return f'Hello {username} !'  # Pass the required route to the decorator.@app.route("/hello")def hello():    return "Hello, Welcome to GeeksForGeeks"    @app.route("/")def index():    return "Homepage of GeeksForGeeks"  if __name__ == "__main__":    app.run(debug=True)
Step to run the application: Run the application using the following command.
python main.py
Output: Open the browser and visit 127.0.0.1:5000/user/geek, you will see the following output.
Additionally, we can also a converter to convert the variable to a specific data type. By default, it is set to sting values. To convert use <converter:variable_name> and following converter types are supported.
sting: It is the default type and it accepts any text without a slash.
int: It accepts positive integers.
float: It accepts positive floating-point values.
path: It is like a string but also accepts slashes.
uuid: It accepts UUID strings.
Example: Consider the following example to demonstrate the converter type.
main.py
from flask import Flask  app = Flask(__name__)  @app.route('/post/<int:id>')def show_post(id):    # Shows the post with given id.    return f'This post has the id {id}'  @app.route('/user/<username>')def show_user(username):    # Greet the user    return f'Hello {username} !'  # Pass the required route to the decorator.@app.route("/hello")def hello():    return "Hello, Welcome to GeeksForGeeks"    @app.route("/")def index():    return "Homepage of GeeksForGeeks"  if __name__ == "__main__":    app.run(debug=True)
Step to run the application: Run the application using the following command.
python main.py
Output: Open the browser and visit 127.0.0.1:5000/post/13, you will see the following output.
The add_url_rule() function – The URL mapping can also be done using the add_url_rule() function. This approach is mainly used in case we are importing the view function from another module. In fact, the app.route calls this function internally. 
Syntax:
add_url_rule(<url rule>, <endpoint>, <view function>) 
Example: In the below example, we will try to map the show_user view function using this approach.
main.py
from flask import Flask  app = Flask(__name__)  def show_user(username):    # Greet the user    return f'Hello {username} !'    app.add_url_rule('/user/<username>', 'show_user', show_user)  if __name__ == "__main__":    app.run(debug=True)
Step to run the application: Run the application using the following command.
python main.py
Output: Open the browser and visit 127.0.0.1:5000/user/pulkit, you will see the following output.
Picked
Python Flask
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?