Basic Routing
A route connects a URL path to a Python function.
A minimal example
Section titled “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"- Visiting
/callshome() - Visiting
/aboutcallsabout()
What can a route return?
Section titled “What can a route return?”A Flask view can return:
- string → response body (HTML/text)
- dict (Flask 2+) → JSON response
flask.Responseobject- tuple forms like
(body, status_code)or(body, status_code, headers)
Example:
@app.route("/health")
def health():
return {"status": "ok"}, 200Trailing slash behavior
Section titled “Trailing slash behavior”These behave differently:
/docs(no slash)/docs/(with slash)
Flask will often redirect automatically depending on how you define the route.
Best practice:
- For “pages”: use
/something/style - For “resources/APIs”: use
/api/itemsstyle
(Consistency matters more than the specific choice.)
Debugging tip: list all routes
Section titled “Debugging tip: list all routes”The CLI command is extremely useful:
flask routesVisualize it
Section titled “Visualize 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
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading