Skip to content

Flask - Routing

Routing is the mechanism that maps URLs (the addresses you type in your browser or that an API client requests) to the specific Python functions in your Flask application that should handle them. This allows you to create clean, memorable URLs for different parts of your web application.

The most common way to define routes in Flask is by using the app.route() decorator. You place this decorator directly above the Python function (often called a view function) that you want to associate with a specific URL rule.

from flask import Flask
app = Flask(__name__)
# Binds the URL '/' to the index() function
@app.route('/')
def index():
return 'Welcome to the Home Page!'
# Binds the URL '/hello' to the hello_world() function
@app.route('/hello')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)

In this example:

  • Visiting http://localhost:5000/ in your browser will trigger the index() function, displaying ‘Welcome to the Home Page!’.
  • Visiting http://localhost:5000/hello will trigger the hello_world() function, displaying ‘Hello, World!’.

Alternatively, you can achieve the same result using the add_url_rule() method of the Flask application object. This is less common for typical view functions but can be useful in certain advanced scenarios or when organizing routes differently.

from flask import Flask
app = Flask(__name__)
def about_page():
return 'This is the About Page.'
# Equivalent to using the @app.route('/about') decorator
app.add_url_rule('/about', 'about', about_page)
# Parameters: URL rule, endpoint name (must be unique), view function
if __name__ == '__main__':
app.run(debug=True)

Here, visiting http://localhost:5000/about will execute the about_page function. The second argument to add_url_rule(), 'about', is the endpoint name. Flask uses endpoints internally, and they are particularly important when using url_for() to generate URLs (covered in another section). When using the @app.route() decorator, the endpoint name defaults to the name of the view function.

For most applications, the @app.route() decorator provides a more concise and readable way to define your URL routes.