Flask URL Variables

URL variables let you capture parts of a URL and use them as inputs to your view function. Instead of creating a separate route for every user or blog post, you write one route that handles all of them.

The Problem Without URL Variables

Imagine a blog with 1,000 posts. Without URL variables, you would need 1,000 separate routes:

# This approach does not scale — don't do this
@app.route('/post/1')
def post_1():
    return 'Post number 1'

@app.route('/post/2')
def post_2():
    return 'Post number 2'
# ... 998 more routes

URL variables solve this completely. One route handles every post:

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'Post number {post_id}'

Syntax for URL Variables

Wrap the variable name in angle brackets inside the route string. The same name becomes a parameter in the function:

@app.route('/user/<username>')
def user_profile(username):
    return f'Profile page of {username}'

When a user visits /user/alice, Flask captures alice as the value of username and passes it to the function.

URL visited:    /user/alice
                      │
              Flask extracts: username = 'alice'
                      │
              user_profile(username='alice') runs
                      │
              Returns: "Profile page of alice"

Type Converters

By default, Flask captures a URL variable as a string. You can tell Flask to convert it to another type automatically using converters:

ConverterTypeExample URLCaptured value
<string:name>String (default)/user/alice'alice'
<int:id>Integer/post/4242
<float:price>Float/item/9.999.99
<path:filepath>String with slashes/files/docs/report.pdf'docs/report.pdf'
<uuid:uid>UUID object/order/3fa85f64-...UUID object

Integer Converter Example

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'Showing post ID: {post_id}'

If a user visits /post/abc, Flask returns a 404 automatically because abc is not an integer. The type converter acts as a guard.

Path Converter Example

@app.route('/files/<path:filepath>')
def serve_file(filepath):
    return f'Serving file: {filepath}'

The path converter is special — it accepts forward slashes inside the variable. Visiting /files/docs/2024/report.pdf captures docs/2024/report.pdf as one string.

Multiple Variables in One Route

A route can contain more than one URL variable:

@app.route('/blog/<int:year>/<int:month>/<string:slug>')
def blog_post(year, month, slug):
    return f'Post from {month}/{year}: {slug}'
URL: /blog/2024/05/my-first-post
         │     │    │
       year  month  slug
        2024   5    'my-first-post'

Accessing Query Parameters

URL variables sit inside the path. Query parameters appear after a ? in the URL. They use a different mechanism:

from flask import Flask, request

app = Flask(__name__)

@app.route('/search')
def search():
    query = request.args.get('q', '')
    return f'You searched for: {query}'

Visiting /search?q=python+flask runs the function with query = 'python flask'. The second argument to .get() is the default value when the parameter is missing.

URL: /search?q=python+flask
              │
       request.args = {'q': 'python flask'}
              │
       query = 'python flask'

Difference: Path Variables vs Query Parameters

FeaturePath VariableQuery Parameter
Position in URL/user/alice/search?q=alice
Use caseIdentifying a specific resourceFiltering or searching
Required?Yes — URL won't match without itNo — optional by nature
Access in FlaskFunction parameterrequest.args.get()

Summary

URL variables transform static routes into dynamic ones. Instead of writing a route for every user or post, you write one route and let the URL carry the variable part. Type converters validate the input automatically and return 404 for wrong types. For optional filters and search terms, query parameters provide a flexible alternative to path variables.

Leave a Comment

Your email address will not be published. Required fields are marked *