Basic Routing
A route connects a URL path to a Python function.
A minimal example
python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Home page"
@app.route("/about")
def about():
return "About page"python
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:
python
@app.route("/health")
def health():
return {"status": "ok"}, 200python
@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:
bash
flask routesbash
flask routesVisualize it
Here’s how Flask resolves an incoming URL to the view function that handles it.
flowchart LR U["Incoming request URL"] --> M["Flask URL map"] M --> V["Matched view function"] V --> R["Response returned"]
🧪 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
