[Python][Flask] Routes vs Endpoints

Understanding Routes vs. Endpoints in Flask

Differences between routes and endpoints in Flask 

  1. Route
    The path that users type in the browser, such as "/blog/" or "/sign_up". It is defined with a decorator:

    @blog.route('/')
    def load_main_page():
        ...

    When someone visits http://localhost:5000/blog/, Flask runs load_main_page().

  2. Endpoint
    The internal name Flask uses to identify the function handling a given route. By default, this is "<blueprint_name>.<function_name>" unless it is renamed. For example, if the blueprint is named blog and the function is load_main_page, the endpoint becomes blog.load_main_page.

  3. url_for()
    This function generates a URL by looking up the endpoint name:

    url_for('blog.load_main_page')

    returns the route "/blog/" if url_prefix='/blog'.

Example

# Blueprint definition
blog = Blueprint('blog', __name__)

@blog.route('/')
def load_main_page():
    # Renders the main page
    return render_template('index.html')

@blog.route('/sign_up', methods=['GET', 'POST'])
def sign_up():
    if request.method == 'POST':
        # Create user, log in, then redirect:
        return redirect(url_for('.load_main_page'))
    return render_template('signup.html')
  • Route:

    • "/" and "/sign_up" are the browser-accessible URLs.

  • Endpoint:

    • blog.load_main_page

    • blog.sign_up

redirect(url_for('.load_main_page'))

The endpoint .load_main_page is internally referenced, and Flask knows to build a URL pointing to "/blog/".

Why It Matters

  • url_for() needs the endpoint name (the function name), not the route path.

  • This separation helps Flask keep the browser-level address (the route) distinct from the code that handles it (the endpoint).

Comments