Routing & Dynamic URL Parameters

🐍 FlaskLesson 3Beginner

Routing is used to bind a URL to a Python function. Dynamic routes allow you to extract variables from the path segment dynamically.

1 Defining Routes & URL Converters
Python — app.py
from flask import Flask

app = Flask(__name__)

# Basic routing
@app.route("/about")
def about():
    return "About Us"

# Dynamic routing with default string converter
@app.route("/user/<username>")
def show_user_profile(username):
    return f"User Profile: {username}"

# Dynamic routing with specific type converters
@app.route("/post/<int:post_id>")
def show_post(post_id):
    return f"Showing Post ID: {post_id}"

@app.route("/path/<path:subpath>")
def show_subpath(subpath):
    return f"Subpath: {subpath}"
2 Allowed Converters
ConverterDescription
stringAccepts any text without a slash (default)
intAccepts positive integers
floatAccepts positive floating point values
pathAccepts text with slashes (matches entire remaining path)
uuidAccepts UUID strings
3 Code Challenge
Challenge: Write a route that accepts a float value /temperature/<float:val> and returns a statement indicating whether it is above or below freezing (0.0 degrees).