0
0
FlaskHow-ToBeginner · 3 min read

How to Use Route Decorator in Flask: Simple Guide

In Flask, use the @app.route() decorator to link a URL path to a Python function that handles requests to that path. This decorator tells Flask which function to run when a user visits the specified URL.
📐

Syntax

The @app.route() decorator is placed above a function to define the URL path it responds to. The string inside route() is the URL path, and the decorated function returns the response shown on that path.

  • @app.route('/path'): Defines the URL path.
  • def function_name(): The function that runs when the URL is visited.
  • return: Sends the response back to the browser.
python
from flask import Flask
app = Flask(__name__)

@app.route('/hello')
def hello():
    return 'Hello, Flask!'

if __name__ == '__main__':
    app.run()
💻

Example

This example shows a simple Flask app with two routes: the home page and a greeting page. Each route uses the @app.route() decorator to connect a URL to a function that returns text.

python
from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the Home Page!'

@app.route('/greet')
def greet():
    return 'Hello, visitor!'

if __name__ == '__main__':
    app.run(debug=True)
Output
Running on http://127.0.0.1:5000/ - Visiting '/' shows: Welcome to the Home Page! - Visiting '/greet' shows: Hello, visitor!
⚠️

Common Pitfalls

Common mistakes when using @app.route() include:

  • Forgetting the leading slash / in the route path, which can cause the route not to match.
  • Defining multiple routes with the same path, which leads to only the last one working.
  • Not returning a response from the function, causing errors.
  • Running the app without the if __name__ == '__main__' guard, which can cause issues when importing.
python
from flask import Flask
app = Flask(__name__)

# Wrong: missing leading slash
@app.route('hello')
def hello_wrong():
    return 'This will not work as expected'

# Right: with leading slash
@app.route('/hello')
def hello_right():
    return 'This works correctly'

if __name__ == '__main__':
    app.run()
📊

Quick Reference

Use this quick reference to remember how to use the route decorator:

UsageDescription
@app.route('/path')Defines the URL path to handle
def function():Function that runs when URL is visited
return 'response'Sends text or HTML back to the browser
@app.route('/path', methods=['GET', 'POST'])Specify HTTP methods allowed
app.run(debug=True)Run app with debug mode for easier development

Key Takeaways

Use @app.route('/path') above a function to link URLs to code in Flask.
Always include a leading slash '/' in the route path string.
Return a response string or HTML from the route function to display content.
Avoid duplicate routes with the same path to prevent conflicts.
Run your Flask app inside the if __name__ == '__main__' block.