Adding URL Rules
route
Decorator to register a view function for a given URL rule.Signature
The URL rule string. Can include variable parts in angle brackets, e.g.,
/user/<username>.List of HTTP methods this route should accept. Defaults to
["GET"]. HEAD and OPTIONS are added automatically.The endpoint name for this route. Defaults to the name of the view function. Used with
url_for() to generate URLs.Additional options are passed to the underlying
werkzeug.routing.Rule object. Common options include:defaults: Dictionary of default values for URL variablessubdomain: Match a specific subdomainstrict_slashes: Whether to redirect trailing slashes (default: True)host: Match a specific host
add_url_rule
Register a URL rule without using a decorator. Equivalent to using@app.route().
Signature
The URL rule string.
The endpoint name to associate with the rule and view function. Used when routing and building URLs. Defaults to
view_func.__name__.The view function to associate with the endpoint name. Can be
None if you register the function later with the @app.endpoint() decorator.Add the
OPTIONS method and respond to OPTIONS requests automatically. Defaults to True.Extra options passed to the
werkzeug.routing.Rule object.endpoint
Decorator to register a view function for a given endpoint. Used if a rule is added without aview_func with add_url_rule().
Signature
The endpoint name to associate with the view function.
URL Variables
URL rules can contain variable parts enclosed in angle brackets. The variable is passed as a keyword argument to the view function.Type Converters
Converters can be used to specify the type of the variable:string- (default) accepts any text without a slashint- accepts positive integersfloat- accepts positive floating point valuespath- likestringbut also accepts slashesuuid- accepts UUID strings
Multiple Variables
URL Building
Useurl_for() to build URLs for endpoints:
HTTP Methods
By default, routes only respond to GET requests. Use themethods parameter to handle other HTTP methods:
@app.get(rule)@app.post(rule)@app.put(rule)@app.delete(rule)@app.patch(rule)
URL Rule Options
defaults
Provide default values for URL variables:strict_slashes
Control whether trailing slashes are enforced:subdomain
Match specific subdomains:SERVER_NAME in the config.
host
Match specific hosts:Rule Object
When you calladd_url_rule(), Flask creates a werkzeug.routing.Rule object. This object contains:
rule: The URL rule stringmethods: Set of HTTP methodsendpoint: The endpoint namedefaults: Default values for variablessubdomain: Subdomain patternhost: Host patternstrict_slashes: Whether trailing slashes matterprovide_automatic_options: Whether OPTIONS is handled automatically
app.url_map:
