How to Create Route in Flask: Simple Guide with Examples
In Flask, you create a route by using the
@app.route() decorator above a function that returns the response for that URL. This connects a URL path to a Python function, so when users visit that path, Flask runs the function and shows its output.Syntax
The basic syntax to create a route in Flask uses the @app.route() decorator followed by a function. The decorator takes the URL path as a string. The function below it defines what to show when that URL is visited.
- @app.route('/path'): Defines the URL path to listen to.
- def function_name(): The function that runs when the path is accessed.
- return: Sends the response back to the browser.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, Flask!' if __name__ == '__main__': app.run()
Example
This example shows a Flask app with two routes: the home page at / and an about page at /about. Each route returns a simple text message.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Welcome to the Home Page!' @app.route('/about') def about(): return 'This is the About Page.' if __name__ == '__main__': app.run()
Output
Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Visiting http://127.0.0.1:5000/ shows: Welcome to the Home Page!
Visiting http://127.0.0.1:5000/about shows: This is the About Page.
Common Pitfalls
Common mistakes when creating routes in Flask include:
- Forgetting the
@app.route()decorator above the function. - Using the same route for multiple functions, which causes conflicts.
- Not returning a response from the function, which leads to errors.
- Running the app without the
if __name__ == '__main__'guard in development.
python
from flask import Flask app = Flask(__name__) # Wrong: Missing decorator # def missing_route(): # return 'No route here' # Right: @app.route('/correct') def correct_route(): return 'This route works' if __name__ == '__main__': app.run()
Quick Reference
| Concept | Description | Example |
|---|---|---|
| @app.route('/path') | Defines the URL path for the route | @app.route('/home') |
| Function below decorator | Runs when the route is accessed | def home(): return 'Hi' |
| Return value | Response sent to the browser | return 'Hello' |
| Running app | Starts the Flask server | app.run() |
Key Takeaways
Use @app.route('/path') decorator to link a URL to a function.
Always return a response from the route function.
Avoid duplicate routes to prevent conflicts.
Use if __name__ == '__main__' to run the app safely in development.
Routes define what users see when they visit specific URLs.