Skip to content

Basic Routing

A route connects a URL path to a Python function.

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

A Flask view can return:

  • string → response body (HTML/text)
  • dict (Flask 2+) → JSON response
  • flask.Response object
  • tuple forms like (body, status_code) or (body, status_code, headers)

Example:

python
@app.route("/health")
def health():
    return {"status": "ok"}, 200

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

(Consistency matters more than the specific choice.)

The CLI command is extremely useful:

bash
flask routes

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

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading