Variable Rules (Dynamic URLs)
Dynamic routes let you capture parts of the URL.
Basic dynamic route
python
from flask import Flask
app = Flask(__name__)
@app.route("/user/<username>")
def user_profile(username: str):
return f"Hello, {username}!"python
from flask import Flask
app = Flask(__name__)
@app.route("/user/<username>")
def user_profile(username: str):
return f"Hello, {username}!"/user/ravi/user/ravi→username = "ravi"username = "ravi"
Type converters
Flask supports converters that validate and convert values:
<int:id><int:id><float:price><float:price><path:subpath><path:subpath>(can include slashes)
Example:
python
@app.route("/post/<int:post_id>")
def post_detail(post_id: int):
return f"Post id: {post_id}"python
@app.route("/post/<int:post_id>")
def post_detail(post_id: int):
return f"Post id: {post_id}"Now:
/post/10/post/10works/post/abc/post/abcreturns 404 (no match)
Multiple variables
python
@app.route("/category/<string:name>/page/<int:page>")
def category(name, page):
return {"category": name, "page": page}python
@app.route("/category/<string:name>/page/<int:page>")
def category(name, page):
return {"category": name, "page": page}Common pitfalls
- Using
<path:...><path:...>when you don’t want slashes (it can match too much) - Forgetting to validate values when types are not enough (e.g., allowed usernames)
- Returning user input directly without escaping in HTML templates (XSS risk)
🧪 Try It Yourself
Exercise 1 – Create a Flask App
Exercise 2 – Dynamic Route
Exercise 3 – Return JSON
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
