Skip to content

Flask - Variable Rules

Flask allows you to define dynamic parts within your URL routes. These variable sections capture segments of the URL and pass them as arguments to your view function. This is essential for creating URLs that represent specific resources, like user profiles, blog posts, or product details.

You mark a variable part in a route rule by enclosing the variable name in angle brackets: <variable_name>.

from flask import Flask
app = Flask(__name__)
# The <username> part is a variable
@app.route('/user/<username>')
def show_user_profile(username):
# The value captured from the URL is passed as the 'username' argument
return f'User Profile: {username}'
if __name__ == '__main__':
app.run(debug=True)

If you run this application and navigate to URLs like:

  • http://localhost:5000/user/Alice -> Displays ‘User Profile: Alice’
  • http://localhost:5000/user/Bob -> Displays ‘User Profile: Bob’

The show_user_profile function receives whatever string comes after /user/ in the URL as its username argument.

By default, variable parts are treated as strings. However, you can specify a converter to process the variable before passing it to the view function. This is useful for type checking and ensuring the URL segment matches an expected format.

Syntax: <converter:variable_name>

ConverterDescription
string(Default) Accepts any text without a slash.
intAccepts positive integers.
floatAccepts positive floating-point numbers.
pathLike string, but also accepts slashes (useful for capturing file paths).
uuidAccepts UUID strings.
from flask import Flask, escape
app = Flask(__name__)
# Expects an integer for post_id
@app.route('/post/<int:post_id>')
def show_post(post_id):
# post_id is guaranteed to be an integer here
return f'Showing Post Number: {post_id}'
# Expects a float for version
@app.route('/version/<float:version>')
def show_version(version):
# version is guaranteed to be a float here
return f'Version: {version:.2f}' # Format float for display
# Expects a path-like structure
@app.route('/files/<path:subpath>')
def show_subpath(subpath):
# subpath can contain slashes, e.g., 'docs/images/logo.png'
# Use escape() for security if rendering user-provided paths
return f'Showing File Path: {escape(subpath)}'
if __name__ == '__main__':
app.run(debug=True)

If you try to visit a URL that doesn’t match the converter type (e.g., /post/abc when int is expected), Flask will return a 404 Not Found error.

Flask’s routing, based on Werkzeug, pays attention to trailing slashes in URL rules:

  • Rule with a trailing slash (e.g., @app.route('/projects/')): This defines the canonical URL ending with a slash. Accessing the URL without the slash (/projects) will result in Flask redirecting the browser to the canonical URL with the slash (/projects/).
  • Rule without a trailing slash (e.g., @app.route('/about')): This defines the canonical URL without the slash. Accessing the URL with a trailing slash (/about/) will result in a 404 Not Found error.

This behavior helps ensure unique URLs for resources, which is beneficial for search engine optimization and prevents duplicate content issues.

from flask import Flask
app = Flask(__name__)
@app.route('/features/') # Canonical URL with trailing slash
def show_features():
return 'List of Features'
@app.route('/contact') # Canonical URL without trailing slash
def contact_us():
return 'Contact Information'
if __name__ == '__main__':
app.run(debug=True)
# Behavior:
# /features/ -> OK (200)
# /features -> Redirects to /features/ (308)
# /contact -> OK (200)
# /contact/ -> Not Found (404)