0
0
Flaskframework~5 mins

Route decorator (@app.route) in Flask

Choose your learning style9 modes available
Introduction

The route decorator connects a web address to a function in your Flask app. It tells the app what to do when someone visits a specific URL.

When you want to show a homepage at '/'
When you want to create a page for '/about' or '/contact'
When you want to handle form submissions at a specific URL
When you want to build an API endpoint that responds to a URL
When you want to organize different pages or actions in your web app
Syntax
Flask
@app.route('/path')
def function_name():
    return 'response'
The string inside @app.route() is the URL path you want to match.
The function below the decorator runs when that URL is visited.
Examples
This sets the homepage at the root URL '/' to show a welcome message.
Flask
@app.route('/')
def home():
    return 'Welcome to the homepage!'
This creates an '/about' page that shows some text.
Flask
@app.route('/about')
def about():
    return 'About us page'
This uses a variable part in the URL to show a user name dynamically.
Flask
@app.route('/user/<username>')
def show_user(username):
    return f'User: {username}'
Sample Program

This Flask app has two routes: the homepage at '/' and a greeting page at '/greet/<name>'. Visiting '/greet/Alice' will show 'Hello, Alice!'.

Flask
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, this is the homepage!'

@app.route('/greet/<name>')
def greet(name):
    return f'Hello, {name}!'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Use @app.route() to connect URLs to functions easily.

Variable parts in URLs use <> brackets, like <username>.

Flask matches routes in the order they are defined, so be careful with overlapping paths.

Summary

@app.route links a URL path to a function in Flask.

It helps your app respond to different web addresses.

You can use fixed or variable URL parts with it.