Skip to content

Variable Rules (Dynamic URLs)

Dynamic routes let you capture parts of the URL.

diagram a converter validates before your view runs mermaid
The type in a rule is not documentation -- it is a filter. A request whose segment does not fit the converter never reaches the function, so the view can assume the value is already the right type. That is why a bad id returns 404 rather than raising inside your code.
python
from flask import Flask
 
app = Flask(__name__)
 
 
@app.route("/user/<username>")
def user_profile(username: str):
    return f"Hello, {username}!"
  • /user/raviusername = "ravi"

Flask supports converters that validate and convert values:

  • <int:id>
  • <float:price>
  • <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}"

Now:

  • /post/10 works
  • /post/abc returns 404 (no match)
python
@app.route("/category/<string:name>/page/<int:page>")
def category(name, page):
    return {"category": name, "page": page}
  • Using <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)

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading