Route / @app.route (Flask)

A Flask route maps a URL path to a Python function using the @app.route decorator. When a request matches the path, Flask calls that function and sends back whatever it returns.

Flask

Routing is how Flask connects the web to your code. The decorator @app.route("/about") tells Flask that requests for /about should run the function directly below it. The function's return value becomes the HTTP response body.

Routes can contain dynamic segments like /user/<username> and can restrict which HTTP methods they accept with the methods argument. By default a route only accepts GET and HEAD requests.

Under the hood Flask stores routes in a URL map and matches incoming requests against it in order of specificity, not declaration order, so /user/admin will win over /user/<name> when both exist.

Syntax

@app.route("/path", methods=["GET", "POST"])
def view():
    ...

Examples

Python — /user/sam returns 'Profile of sam'

@app.route("/about")
def about():
    return "<h1>About us</h1>"

@app.route("/user/<name>")
def profile(name):
    return f"Profile of {name}"

Learn it in a lesson

See also

Back to the Dictionary