Basic Routing
A route connects a URL path to a Python function.
A minimal example
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Home page"
@app.route("/about")
def about():
return "About page"from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Home page"
@app.route("/about")
def about():
return "About page"- Visiting
//callshome()home() - Visiting
/about/aboutcallsabout()about()
What can a route return?
A Flask view can return:
- string β response body (HTML/text)
- dict (Flask 2+) β JSON response
flask.Responseflask.Responseobject- tuple forms like
(body, status_code)(body, status_code)or(body, status_code, headers)(body, status_code, headers)
Example:
@app.route("/health")
def health():
return {"status": "ok"}, 200@app.route("/health")
def health():
return {"status": "ok"}, 200Trailing slash behavior
These behave differently:
/docs/docs(no slash)/docs//docs/(with slash)
Flask will often redirect automatically depending on how you define the route.
Best practice:
- For βpagesβ: use
/something//something/style - For βresources/APIsβ: use
/api/items/api/itemsstyle
(Consistency matters more than the specific choice.)
Debugging tip: list all routes
The CLI command is extremely useful:
flask routesflask routesπ§ͺ Try It Yourself
Exercise 1 β Create a Flask App
Exercise 2 β Dynamic Route
Exercise 3 β Return JSON
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
