📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Flask Web Framework Routing in Flask

Routing in Flask

5 min read Quiz at the end
Map URLs to Python functions with @app.route(), URL converters, HTTP methods, and url_for().

Routing

from flask import Flask, request, redirect, url_for

app = Flask(__name__)

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

# URL parameters
@app.route("/users/")
def user(user_id):
    return "User " + str(user_id)

@app.route("/posts/")
def post(slug):
    return "Post: " + slug

# HTTP methods
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        return process_login()
    return render_template("login.html")

# Redirect and url_for
@app.route("/old-path")
def old():
    return redirect(url_for("index"))

# Dynamic URL building
url_for("user", user_id=42)  # /users/42
Topic Quiz · 3 questions

Test your understanding before moving on

1. How do you accept both GET and POST on a Flask route?
💡 methods=["GET","POST"] in the route decorator accepts both HTTP methods.
2. How do you capture a URL segment as an integer?
💡 <int:id> is the Flask converter syntax ensuring the value is an integer.
3. What does url_for() do?
💡 url_for("function_name", param=val) generates the correct URL for that view.