Dynamic URLs & Type Converters
Dynamic URLs & Type Converters
Routing connects incoming client URLs to corresponding Python view functions. In real-world web applications, URLs are rarely completely static; they contain dynamic resource identifiers such as user IDs, article slugs, or UUIDs.
1. Declaring Dynamic URL Parameters
To define dynamic URL parameters, place a variable name inside angle brackets <variable_name> within @app.route():
If a client requests /user/sumit, Flask extracts 'sumit' and passes it as the username argument to show_user_profile().
2. Built-in URL Type Converters
By default, URL segments are parsed as strings. Flask provides built-in type converters (<converter:variable_name>) to validate and typecast incoming parameters automatically:
| Converter | Type | Description | Example |
|---|---|---|---|
string | str | Accepts any text without slashes (default) | <string:category> |
int | int | Accepts positive integers only; typecasts to int | <int:product_id> |
float | float | Accepts positive floating point numbers | <float:discount_rate> |
path | str | Accepts any text, including slashes | <path:file_subpath> |
uuid | uuid.UUID | Accepts RFC 4122 UUID strings | <uuid:order_id> |
Practical Code Example:
If a client visits /products/abc (a non-integer), Flask's converter automatically rejects the request with an HTTP 404 Not Found without ever invoking get_product().
3. Unique URLs and Trailing Slash Redirection
Flask enforces canonical, unique URLs:
- 1Canonical folder URL (
/projects/): If a user visits/projectswithout a trailing slash, Flask automatically sends an HTTP308 Permanent Redirectto/projects/. - 2Canonical file URL (
/about): If a user visits/about/with a trailing slash, Flask returns an HTTP404 Not Found.
This rule prevents duplicate content penalties in search engine optimization (SEO).
4. Custom Regex Converters
When built-in converters are insufficient, you can create custom converters by subclassing werkzeug.routing.BaseConverter:
Practice Quiz
@app.route('/user/<username>'))?/) within the URL segment?/orders/hello for a route defined as @app.route('/orders/<int:order_id>')?/projects to /projects/ when the route is defined with a trailing slash?Handling HTTP Methods (GET, POST, PUT, DELETE)
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Flask CLI & Environment Configuration | Handling HTTP Methods (GET, POST, PUT, DELETE) |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.