HOWTO · Flask

How to Create Dynamic URL Using url_for in Flask

Learn how Flask url_for() builds URLs from view endpoints, includes dynamic route values, supports redirects, and creates Jinja links.

On this page

In Flask, url_for() builds a URL for an endpoint, usually the name of a view function. Pass route values as keyword arguments to fill a dynamic path. The function returns a URL string; to send a browser to that URL, return a redirect() response from a view.

How url_for() Builds a URL

Flask registers each view under an endpoint. By default, the endpoint is the view function’s name, so url_for("index") refers to a view named index. Flask looks up the route for that endpoint and builds the URL, which keeps links tied to route definitions instead of duplicating path strings throughout an application.

The result is a path such as / or /users/Harry. If a route has variable segments, supply their values using matching keyword names. Additional values that are not part of the route are added as query parameters. Generating a URL does not make a request or redirect a visitor.

Build a URL from a View Function

The following small app defines a home view, a profile view, a redirecting view, and a Jinja page. Its test client requests the Jinja page and checks the redirect response without starting a server. Install Flask in the Python environment before running it. In the supplied runtime, the test client rendered the link and received a 302 response with /users/Harry as its Location header.

Run this example:

from flask import Flask, redirect, render_template_string, url_for

app = Flask(__name__)


@app.get("/")
def index():
    return "Home"


@app.get("/users/<string:user_name>")
def profile(user_name):
    return f"Profile: {user_name}"


@app.get("/go")
def go():
    return redirect(url_for("profile", user_name="Harry"))


@app.get("/links")
def links():
    return render_template_string(
        '<a href="{{ url_for(\'profile\', user_name=\'Josh\') }}">Profile</a>'
    )


with app.test_client() as client:
    page = client.get("/links")
    print(page.get_data(as_text=True))
    response = client.get("/go", follow_redirects=False)
    print(response.status_code)
    print(response.headers["Location"])
<a href="/users/Josh">Profile</a>
302
/users/Harry

The endpoint argument is profile, the view function name. When Flask handles /go, url_for() builds the profile path and redirect() returns a redirect response to it. The test client prints the rendered link, then the redirect status and its Location header. url_for("index") would build the home path from the same app.

Pass Dynamic Route Values

The route /users/<string:user_name> declares a variable named user_name; the call url_for("profile", user_name="Harry") passes a value for that same variable. Flask inserts the value into the path and applies URL encoding when needed. Keep the endpoint and each route variable name aligned with the view and the keyword arguments, or URL building cannot match the route.

For a route such as /articles/<int:article_id>, pass an integer with url_for("article", article_id=42). Values not consumed by a route variable, such as sort="recent", become query parameters. Use route variables for path structure and extra keyword arguments for query data.

Redirect with a Generated URL

Inside a view, return redirect(url_for("profile", user_name="Harry")). url_for() supplies the destination path, while redirect() creates the HTTP response that tells the browser to navigate there. The /go view in the example uses this pattern. Returning only url_for(...) would send the URL string as the response body; it would not navigate the browser.

This distinction is useful when routes change: the redirect still targets the endpoint’s registered route, so the view does not need a hard-coded path. Choose the redirect behavior intentionally, since a redirect is a response to the current request and the destination is requested separately by the browser.

In a Jinja template, use the same endpoint and route values inside an anchor’s href:

<a href="{{ url_for('profile', user_name='Josh') }}">Profile</a>

Here, profile matches the view name and user_name fills its required route segment. The runnable example renders this template string at /links, so the generated link points to the profile route. For a template stored in a file, return it with Flask’s render_template("index.html"); place that file in the application’s templates directory. Do not pass a route value that the destination endpoint does not declare, and use the exact endpoint spelling used by the application.