Skip to content

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 // calls home()home()
  • Visiting /about/about calls about()about()

What can a route return?

A Flask view can return:

  • string → response body (HTML/text)
  • dict (Flask 2+) → JSON response
  • flask.Responseflask.Response object
  • 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"}, 200
python
@app.route("/health")
def health():
    return {"status": "ok"}, 200

Trailing 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/items style

(Consistency matters more than the specific choice.)

Debugging tip: list all routes

The CLI command is extremely useful:

bash
flask routes
bash
flask routes

Visualize it

Here’s how Flask resolves an incoming URL to the view function that handles it.

diagram URL resolution flow mermaid
How Flask matches a request URL to a view function

🧪 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 coffee

Was this page helpful?

Let us know how we did