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
pathconverter; 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
| Converter | Description | Example |
|---|---|---|
| string | Default, accepts any text except slash | /user/ |
| int | Accepts integers | /post/ |
| float | Accepts floating point numbers | /price/ |
| path | Like string but accepts slashes | /path/ |
| uuid | Accepts 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.