Routing
Routing binds URLs to view functions, determining which code handles a request to a given path. Flask declares routes with decorators, and they are the first building block of any application.
Basic Usage
@app.get / @app.post / @app.put / @app.delete / @app.patch are shortcut decorators added in Flask 2.0. Requests using an undeclared method get a 405 Method Not Allowed.
URL Parameters and Converters
Capture path segments with <variable> and optionally specify a type converter:
Built-in converters: string (default, no slashes), int, float, path (allows slashes), uuid. A type mismatch returns 404 automatically — no manual validation needed.
Building URLs: url_for
Never hardcode URLs in code or templates — generate them from endpoint names with url_for():
The endpoint name defaults to the view function name; blueprint endpoints are prefixed with the blueprint name, e.g. url_for("blog.list_posts").
Redirects and abort
Trailing Slash Behavior
- A route defined as
/projects/(with trailing slash): visiting/projectstriggers a 308 redirect to/projects/. - A route defined as
/about(no trailing slash): visiting/about/returns 404.
Keeping a consistent style across the team avoids extra redirect round trips.
Custom Converters
For regex or special matching, register a custom converter:
Things to Watch For
- Routes are matched by registration order and specificity; avoid defining overlapping, ambiguous paths.
- View function names (endpoint names) must be unique — duplicates raise an error at startup.
- The
flask routescommand lists every route in the application, which is handy for debugging.