0
0
FlaskHow-ToBeginner · 4 min read

How to Use Variable Rules in Flask for Dynamic URLs

In Flask, use <variable_name> in route paths to capture parts of the URL as variables. These variables are passed as arguments to the view function, allowing dynamic content based on the URL.
📐

Syntax

Flask uses angle brackets <> in route paths to define variable parts. You can specify a variable name and optionally a converter type to control the variable's data type.

  • <variable_name>: captures a string by default.
  • <type:variable_name>: captures and converts the variable to the specified type.

Common converters include string (default), int, float, path (like string but accepts slashes), and uuid.

python
@app.route('/user/<username>')
def user_profile(username):
    pass

@app.route('/post/<int:post_id>')
def show_post(post_id):
    pass
💻

Example

This example shows how to create routes with variable rules to greet users by name and show posts by numeric ID.

python
from flask import Flask

app = Flask(__name__)

@app.route('/hello/<name>')
def hello(name):
    return f"Hello, {name}!"

@app.route('/post/<int:post_id>')
def post(post_id):
    return f"Post number {post_id}"

if __name__ == '__main__':
    app.run(debug=True)
Output
When visiting /hello/Alice, the page shows: Hello, Alice! When visiting /post/42, the page shows: Post number 42
⚠️

Common Pitfalls

  • Not specifying a converter when expecting a number causes the variable to be treated as a string, which may break logic.
  • Using variable names that conflict with Python keywords or function parameters can cause errors.
  • For paths that include slashes, use the path converter; otherwise, Flask stops at the first slash.
python
from flask import Flask

app = Flask(__name__)

# Wrong: post_id treated as string
@app.route('/post/<post_id>')
def post_wrong(post_id):
    return f"Post ID plus one: {int(post_id) + 1}"  # Fixed to convert string to int

# Right: specify int converter
@app.route('/post/<int:post_id>')
def post_right(post_id):
    return f"Post ID plus one: {post_id + 1}"
📊

Quick Reference

ConverterDescriptionExample
stringDefault, accepts any text except slash/user/
intAccepts integers/post/
floatAccepts floating point numbers/price/
pathLike string but accepts slashes/path/
uuidAccepts UUID strings/item/

Key Takeaways

Use angle brackets <> in routes to capture URL parts as variables.
Specify converters like int or float to ensure correct variable types.
Variables in routes become parameters in the view function automatically.
Use path converter to capture URL parts containing slashes.
Avoid naming variables with Python keywords or conflicting names.