Flask Url Route Registrations Api
## Flask URL Route Registrations API
Flask provides three primary ways to define routing rules for your web application:
1. The `@app.route()` decorator (most common).
2. The `app.add_url_rule()` method (useful for class-based views or modular registration).
3. Direct manipulation of `app.url_map`.
---
## URL Variable Converters
You can capture parts of the URL and pass them as arguments to your view function. Flask uses converters to parse these variables and cast them to specific Python types.
| Converter | Syntax | Matching Rules | Python Type |
| :--- | :--- | :--- | :--- |
| `string` | `` or `` | Any text without a slash `/` (Default) | `str` |
| `int` | `` | Positive integers | `int` |
| `float` | `` | Positive floating-point numbers | `float` |
| `path` | `` | Any text (including slashes `/`) | `str` |
| `any` | `` | Matches any of the items specified in the list | `str` |
| `uuid` | `` | Standard UUID format | `str` |
---
## The `add_url_rule` Parameters
The `add_url_rule()` method is the underlying mechanism behind the `@app.route` decorator. Understanding its parameters gives you fine-grained control over routing behavior.
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `rule` | `str` | The URL rule string, e.g., `"/user/"` |
| `endpoint` | `str` | The endpoint name. Defaults to the view function's name. `url_for` references this name to generate URLs. |
| `view_func` | `callable` | The view function to bind. Optional; can be registered later in the `view_functions` dictionary. |
| `defaults` | `dict` | Default values for URL variables, e.g., `defaults={"page": 1}` |
| `subdomain` | `str` | Subdomain matching rule. Requires `subdomain_matching` to be enabled on the app. |
| `methods` | `list` | Allowed HTTP methods. Defaults to `` (`HEAD` and `OPTIONS` are automatically added). |
| `host` | `str` | Hostname matching rule. Requires `host_matching` to be enabled on the app. |
---
## Trailing Slash Behavior
Flask handles trailing slashes strictly to ensure unique URLs and improve SEO.
| Rule | Accessing without `/` | Accessing with `/` |
| :--- | :--- | :--- |
| `@app.route("/projects/")` | `308 Permanent Redirect` to `/projects/` | `200 OK` (Normal Access) |
| `@app.route("/about")` | `200 OK` (Normal Access) | `404 Not Found` |
---
## Default Values in Routes
You can define optional URL variables by providing default values using the `defaults` parameter.
### Example
```python
from flask import Flask
app = Flask(__name__)
# Both URLs point to the same view function.
# Accessing /users/ is equivalent to accessing /users/page/1
@app.route("/users/", defaults={"page": 1})
@app.route("/users/page/")
def show_users(page):
return f"Showing page {page}"
# Request to /users/ β page=1
# Request to /users/page/3 β page=3
```
> **Note:** If both the default route and the variable route exist, accessing the URL with the explicit default value (e.g., `/users/page/1`) will be redirected via a `308 Permanent Redirect` to its simplified form (`/users/`).
---
## Custom URL Converters
If the built-in converters do not meet your requirements, you can create a custom converter by subclassing `BaseConverter` from Werkzeug.
### Example: A List Converter
The following example demonstrates how to create a custom converter that parses a comma-separated string in the URL into a Python list, and vice versa.
```python
from flask import Flask
from werkzeug.routing import BaseConverter
app = Flask(__name__)
# 1. Define the custom converter
class ListConverter(BaseConverter):
"""Matches a comma-separated list, e.g., /tags/python,flask,web"""
def to_python(self, value):
# Converts the URL string into a Python list passed to the view
return value.split(",")
def to_url(self, values):
# Converts a Python list back into a URL string when using url_for()
return ",".join(values)
# 2. Register the converter in the app's url_map
app.url_map.converters = ListConverter
# 3. Use the custom converter in a route
@app.route("/tags/")
def show_tags(tags):
# 'tags' is received as a Python list: ["python", "flask", "web"]
return f"Tags: {', '.join(tags)}"
```
YouTip