Skip to content

URL Building (url_for)

Hardcoding routes like "/user/123" is fragile.

If you rename the route later, you must update every place that used the string.

Flask’s best practice is to generate URLs with url_for().

diagram build URLs from the endpoint, never by concatenating strings mermaid
url_for goes from an endpoint name and some values to a path, using the same rules the router uses to match. That means a route can be renamed in one place, extra keyword arguments become the query string, and values are percent-encoded on the way in. It is also the only form that stays correct once the app is mounted under a prefix or served as a blueprint.
python
from flask import Flask, url_for
 
app = Flask(__name__)
 
 
@app.route("/")
def home():
    profile_url = url_for("profile", username="ravi")
    return f"Profile link: {profile_url}"
 
 
@app.route("/user/<username>")
def profile(username):
    return f"Profile: {username}"

Key idea:

  • You pass the endpoint name (usually the function name)
  • And any variables required by the route
  • avoids broken links after refactors
  • supports query parameters cleanly
  • supports Blueprints (namespaced endpoints)
python
url_for("search", q="flask", page=2)

Output (conceptually):

  • /search?q=flask&page=2

You’ll use:

python
url_for("static", filename="styles.css")

That’s how templates should reference CSS/JS.

Run:

bash
flask routes

It lists endpoints and URL rules.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading