Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 72 ยท Routing and Views

Building URLs with url_for

Learn how Flask's url_for builds URLs from endpoint names, fills in URL variables, adds query strings and anchors, makes external links and finds static files.

Sooner or later every page links to another page. You could type the address by hand, as in <a href="/users/7">, but then the URL lives in two places: the route that serves it and every link that points at it. Rename the route and the links silently break.

Flask solves this with url_for(). You give it the name of a view (its endpoint) and the values for any URL variables, and it builds the address from the route definition. Change the route and every generated link follows. In this lesson you'll build paths, query strings, anchors and full external URLs, link to static files, and learn why url_for sometimes complains that it is "working outside of application context".

The basic idea

By default, a route's endpoint is the name of the view function. url_for("show_user", user_id=7) looks up the endpoint show_user, sees that its rule is /users/<int:user_id>, and substitutes the value.

flowchart LR
    A["url_for('show_user', user_id=7)"] --> B["url_map lookup:<br/>endpoint 'show_user'"]
    B --> C["rule: /users/&lt;int:user_id&gt;"]
    C --> D["'/users/7'"]

url_for runs routing in reverse: from endpoint and values to a URL.

The only catch is that url_for needs to know about your application, so it must run inside a request, or inside an application context. In a real app that is automatic whenever a view runs. In the examples here we use app.test_request_context(), which pretends a request is happening without any server.

Python Building URLs from endpoint names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the third line. search has no URL variables, so the extra keyword arguments q and page become the query string, and the space in flask tips is encoded for you. The _anchor argument appends a #fragment. Both are handled by Werkzeug, the library underneath Flask, so you never have to escape anything yourself.

Arguments that start with an underscore are reserved for url_for itself:

Argument Effect
_external=True Produce a full URL with scheme and host
_scheme="https" Force a scheme (needs _external=True, or Flask raises an error)
_anchor="top" Append #top
_method="POST" Pick the rule that accepts that method, when several rules share an endpoint

Endpoints and their names

The endpoint is just a string key into the app's URL map. Normally you never think about it because it equals the function name. But you can choose it yourself with the endpoint argument, and you can list every rule the app knows with app.url_map.

Python Inspecting the URL map and handling errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two things to notice. First, the function whatever_name was registered under the endpoint about_page, so url_for("whatever_name") fails with a BuildError. Second, BuildError is also what you get when you forget a required URL variable. When a link breaks in a template, this is almost always the reason, and the error message lists the endpoint and the arguments you passed.

A blueprint prefixes its endpoints with its own name, such as blog.show_post. Inside the same blueprint you can write a leading dot, url_for(".show_post"), as a shortcut. You'll meet this in Blueprints.

Why not hard-code URLs?

There are four practical reasons to always use url_for:

  • One source of truth. The route decorator is the only place that says what the URL looks like.
  • Escaping is automatic. Spaces, slashes, & and non-ASCII characters in values are encoded correctly.
  • It respects deployment. If the app is mounted under a prefix (say /shop), generated URLs include it. Hand-typed ones do not.
  • Broken links fail loudly. A typo in the endpoint raises BuildError in development instead of producing a dead link in production.

The same helper works in templates. Jinja has url_for available as a global, so you write {{ url_for("show_user", user_id=7) }} directly in HTML. The next section shows it in action; templates are covered fully in Jinja Templates Basics.

Static files

Flask automatically adds a route with the endpoint static for files in the app's static folder. To link to static/css/site.css, pass the path as the filename argument:

HTML
<link rel="stylesheet" href="{{ url_for('static', filename='css/site.css') }}">

This produces /static/css/site.css. We cover caching, cache busting and serving other folders in Static Files and Assets.

External URLs and SERVER_NAME

A relative URL such as /users/7 is right for links inside your pages. But sometimes you need the full address, with scheme and host: in an email, in a JSON response, or in a Location header. That is what _external=True is for.

During a real request, Flask takes the host from the incoming Host header. Outside a request (in a background job or a command-line script) there is no header to read. For that case, set SERVER_NAME and use an application context:

Python External URLs, schemes and SERVER_NAME

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The RuntimeError appears because the app context alone cannot know the hostname. Once SERVER_NAME is set, the context can build external URLs, and PREFERRED_URL_SCHEME supplies the scheme (the default is http).

Be careful before you set SERVER_NAME on an app that serves real traffic. When it is set, Flask only matches requests whose Host header equals that value, and requests for other hostnames (including localhost during development) fail with 404. Many apps skip it and only set it for command-line tasks, or build external URLs from a configured base URL of their own.

Outside a request: the context rules

url_for raises RuntimeError: Unable to build URLs outside an active request without 'SERVER_NAME' configured if neither context exists. Three situations give you a context automatically:

  1. A view function, template or hook that Flask calls while handling a request.
  2. A with app.test_request_context(): block, which is ideal for experiments and tests.
  3. A with app.app_context(): block, which allows url_for only with SERVER_NAME set.

More on how these contexts are pushed and popped is in How a Request Flows Through Flask.

Redirecting with url_for

The most common partner of url_for is redirect. After handling a form, you send the browser to another endpoint instead of typing its path:

Python
from flask import redirect, url_for

@app.post("/login")
def login():
    # ... check the credentials ...
    return redirect(url_for("dashboard"))

Responses and redirects get their own treatment in Responses, Status Codes and Headers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does url_for('show_user', user_id=7) return for the rule /users/<int:user_id>?

    url_for only builds a URL string from the endpoint and values. It does not call the view or send a redirect.
  2. 2. You call url_for('search', q='a b', page=2) and search has no URL variables. Where do q and page go?

    Keyword arguments that match no URL variable are appended as an encoded query string.
  3. 3. A view is declared with @app.route('/about', endpoint='about_page') on a function named about. Which call works?

    The endpoint argument replaces the default name, so the function name is no longer an endpoint.
  4. 4. Why does url_for(..., _external=True) fail inside a bare app.app_context() block with no SERVER_NAME?

    Without a request there is no Host header. Setting SERVER_NAME gives the context a host to use.

Summary

  • url_for(endpoint, **values) builds a URL from a view's endpoint name, which defaults to the function name.
  • Values matching URL variables fill the path; extra keywords become the query string. _anchor, _external, _scheme and _method are special.
  • BuildError means an unknown endpoint or a missing URL variable.
  • url_for('static', filename='...') links to files in the static folder.
  • External URLs need a request, or SERVER_NAME plus an application context. Setting SERVER_NAME changes host matching, so use it deliberately.
  • Use app.test_request_context() to experiment and to test URL building without a server.

Next: Responses, Status Codes and Headers, everything a view can return.