Variable Rules (Dynamic URLs)
Dynamic routes let you capture parts of the URL.
flowchart TD
A["GET /post/abc"] --> B["match against /post/<int:pid>"]
B --> C{"does 'abc' parse as an int?"}
C -->|no| D["404 -- the view is never called"]
C -->|yes| E["pid = 42, a real int"]
E --> F["your view runs"]
G["converters"] --> H["string -- default, no slashes"]
G --> I["int / float -- numeric, and converted"]
G --> J["path -- like string but DOES match slashes"]
G --> K["uuid -- a canonical UUID"]
Basic dynamic route
Section titled “Basic dynamic route”from flask import Flask
app = Flask(__name__)
@app.route("/user/<username>")
def user_profile(username: str):
return f"Hello, {username}!"/user/ravi→username = "ravi"
Type converters
Section titled “Type converters”Flask supports converters that validate and convert values:
<int:id><float:price><path:subpath>(can include slashes)
Example:
@app.route("/post/<int:post_id>")
def post_detail(post_id: int):
return f"Post id: {post_id}"Now:
/post/10works/post/abcreturns 404 (no match)
Multiple variables
Section titled “Multiple variables”@app.route("/category/<string:name>/page/<int:page>")
def category(name, page):
return {"category": name, "page": page}Common pitfalls
Section titled “Common pitfalls”- 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)
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading