0
0
FlaskHow-ToBeginner · 3 min read

How to Use Dynamic Routes in Flask for Flexible URLs

In Flask, you create a dynamic route by adding variable parts in the route URL using angle brackets like <variable_name>. Flask passes these variables as arguments to your view function, letting you handle flexible URLs easily.
📐

Syntax

Dynamic routes in Flask use angle brackets <> to capture parts of the URL as variables. You can specify the variable name and optionally its type like <int:id> for integers.

  • Route pattern: The URL path with variable parts inside <>.
  • Variable name: The name inside brackets that becomes a function parameter.
  • Type converter (optional): Specifies the variable type like int, float, or path.
python
@app.route('/user/<username>')
def user_profile(username):
    pass

@app.route('/post/<int:post_id>')
def show_post(post_id):
    pass
💻

Example

This example shows a Flask app with a dynamic route that captures a username from the URL and displays a greeting message using that username.

python
from flask import Flask

app = Flask(__name__)

@app.route('/hello/<username>')
def hello_user(username):
    return f"Hello, {username}! Welcome to Flask dynamic routes."

if __name__ == '__main__':
    app.run(debug=True)
Output
When you visit http://127.0.0.1:5000/hello/Alice in your browser, the page shows: Hello, Alice! Welcome to Flask dynamic routes.
⚠️

Common Pitfalls

Common mistakes when using dynamic routes include:

  • Not matching the variable name in the route and function parameter.
  • Using the wrong type converter, causing 404 errors if the URL part doesn't match.
  • Forgetting to handle types properly, especially when expecting integers.

Always ensure your function parameters match the route variables exactly.

python
from flask import Flask

app = Flask(__name__)

# Wrong: function parameter name does not match route variable
@app.route('/item/<int:item_id>')
def get_item(item_id):  # fixed parameter name
    return f"Item {item_id}"

# Correct:
@app.route('/item/<int:item_id>')
def get_item(item_id):
    return f"Item {item_id}"
📊

Quick Reference

Summary tips for dynamic routes in Flask:

  • Use <variable> to capture strings.
  • Use <int:variable> for integers.
  • Use <float:variable> for floating-point numbers.
  • Use <path:variable> to capture slashes in variables.
  • Match route variables exactly in function parameters.

Key Takeaways

Use angle brackets <> in route URLs to define dynamic parts.
Match the variable names in the route and the view function parameters exactly.
Specify type converters like int or float to restrict variable types.
Dynamic routes let you create flexible URLs that respond to user input.
Test your routes to avoid 404 errors caused by type mismatches or name errors.