Skip to content

Variable Rules (Dynamic URLs)

Dynamic routes let you capture parts of the URL.

Basic dynamic route

from flask import Flask
 
app = Flask(__name__)
 
 
@app.route("/user/<username>")
def user_profile(username: str):
    return f"Hello, {username}!"
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:

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

Now:

  • /post/10/post/10 works
  • /post/abc/post/abc returns 404 (no match)

Multiple variables

@app.route("/category/<string:name>/page/<int:page>")
def category(name, page):
    return {"category": name, "page": page}
@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 coffee

Was this page helpful?

Let us know how we did