Skip to content

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 // 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:

@app.route("/health")
def health():
    return {"status": "ok"}, 200
@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:

flask routes
flask 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 coffee

Was this page helpful?

Let us know how we did