0
0
Flaskframework~5 mins

Route with dynamic parameters in Flask

Choose your learning style9 modes available
Introduction

Dynamic parameters let your web app handle different inputs in the URL. This helps show different pages or data without making many routes.

Showing user profiles by user ID in the URL
Displaying blog posts based on post titles or IDs
Filtering products by category or product ID in an online store
Accessing details of an event by event ID
Creating URLs that change based on user input or selections
Syntax
Flask
@app.route('/path/<parameter>')
def function_name(parameter):
    # use parameter inside function
    return f"Value is {parameter}"

Use in the route to capture part of the URL as a variable.

The function receives this variable as an argument to use inside.

Examples
This captures the username from the URL and shows it.
Flask
@app.route('/user/<username>')
def show_user(username):
    return f"User: {username}"
This captures a number as post_id and uses it inside the function.
Flask
@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f"Post ID: {post_id}"
This captures a decimal number from the URL.
Flask
@app.route('/item/<float:price>')
def show_price(price):
    return f"Price: {price}"
Sample Program

This Flask app greets anyone by name from the URL. For example, visiting /hello/Alice shows "Hello, Alice!".

Flask
from flask import Flask

app = Flask(__name__)

@app.route('/hello/<name>')
def hello(name):
    return f"Hello, {name}!"

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

You can specify types like int, float, or path for parameters to control what is accepted.

If you don't specify a type, the parameter is treated as a string.

Dynamic routes help keep your app clean and flexible by reusing one route for many inputs.

Summary

Dynamic parameters let routes accept variable parts in the URL.

Use <parameter> in the route and receive it as a function argument.

Specify types like int or float to control input format.