Dynamic Route / URL Converter (Flask)

A dynamic route in Flask captures part of the URL as a variable using angle brackets, like /post/<int:id>. The captured value is passed into the view function as an argument.

Flask

Dynamic routes let one view handle many URLs. The placeholder <id> grabs whatever appears in that URL position and passes it to your function as a keyword argument of the same name.

You can attach a converter to enforce and cast the type: <int:id> only matches digits and gives you an int, <float:price> matches decimals, <path:subpath> matches slashes too, and the default <string> matches any text without a slash. A non-matching value produces a 404 rather than reaching your code.

Converters keep your view code clean because you never have to manually validate or cast the captured value — Flask rejects bad input before the function runs.

Syntax

@app.route("/post/<int:post_id>")
def show(post_id):
    ...

Examples

Python — /post/42 -> 'Post #42 (type int)'; /post/abc -> 404

@app.route("/post/<int:post_id>")
def show_post(post_id):
    return f"Post #{post_id} (type {type(post_id).__name__})"

Learn it in a lesson

See also

Back to the Dictionary