What is URL building and how do you use `url_for()`?

Beginner

Answer

url_for() generates URLs for routes by endpoint name, providing URL reversal:

from flask import url_for

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

@app.route('/')
def index():
    # Generate URL for user_profile endpoint
    profile_url = url_for('user_profile', username='john')
    return f'<a href="{profile_url}">John\'s Profile</a>'

Benefits include automatic URL updates when routes change and proper URL escaping.