Python Notes
Master Flask URL routing — dynamic routes, URL converters, HTTP methods, redirects, URL building with url_for, and RESTful route design patterns in Python Flask.
Routing is the process of mapping URLs to view functions. Flask's routing system is flexible and powerful, allowing you to create clean, RESTful APIs and web applications.
Basic Routing
The simplest route maps a URL path to a Python function:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Home Page'
@app.route('/hello')
def hello():
return 'Hello!'
@app.route('/about')
def about():
return 'About Page'Dynamic Routes
Dynamic routes capture parts of the URL as variables:
from flask import Flask
app = Flask(__name__)
# String parameter (default)
@app.route('/user/<username>')
def show_user(username):
return f'User: {username}'
# Integer parameter
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post ID: {post_id}'
# Float parameter
@app.route('/price/<float:amount>')
def show_price(amount):
return f'Price: ${amount:.2f}'
# Path parameter (allows slashes)
@app.route('/files/<path:filepath>')
def show_file(filepath):
return f'File: {filepath}'Visit /user/john → "User: john" Visit /post/42 → "Post ID: 42" Visit /files/docs/python/basics.txt → "File: docs/python/basics.txt"
URL Converters
Flask provides built-in URL converters:
| Converter | Description | Example |
|---|---|---|
string | Default, any text without slash | <string:name> |
int | Positive integers | <int:id> |
float | Positive floating-point values | <float:price> |
path | Like string but accepts slashes | <path:subpath> |
uuid | UUID strings | <uuid:token> |
from flask import Flask
import uuid
app = Flask(__name__)
@app.route('/item/<int:item_id>')
def get_item(item_id):
if item_id <= 0:
return 'Invalid ID', 400
return f'Item #{item_id}'
@app.route('/token/<uuid:token>')
def verify_token(token):
return f'Token: {token}'
# Multiple parameters
@app.route('/category/<string:category>/product/<int:product_id>')
def get_product(category, product_id):
return f'Category: {category}, Product: {product_id}'Custom URL Converters
Create your own URL converters for complex patterns:
HTTP Methods
By default, routes only respond to GET requests. Use methods to specify accepted HTTP methods:
RESTful Route Design
Flask's routing is perfect for RESTful APIs:
URL Building with url_for
Always use url_for() to generate URLs — it handles URL encoding and works even if you change route paths:
from flask import Flask, url_for, redirect, request
app = Flask(__name__)
@app.route('/')
def index():
return 'Home'
@app.route('/login')
def login():
return 'Login Page'
@app.route('/user/<username>')
def user_profile(username):
return f'Profile: {username}'
@app.route('/dashboard')
def dashboard():
# Check if user is logged in
if not request.args.get('logged_in'):
# Redirect to login using url_for
return redirect(url_for('login'))
return 'Dashboard'
# Using url_for in code
with app.test_request_context():
print(url_for('index')) # /
print(url_for('login')) # /login
print(url_for('user_profile', username='john')) # /user/john
print(url_for('user_profile', username='john', page=2)) # /user/john?page=2
print(url_for('login', next='/dashboard')) # /login?next=%2FdashboardRedirects
Request Object
The request object contains all incoming request data:
Blueprint Routing
Blueprints allow you to organize routes into separate modules:
# app.py
from flask import Flask
from blueprints.users import users_bp
from blueprints.products import products_bp
app = Flask(__name__)
# Register blueprints
app.register_blueprint(users_bp)
app.register_blueprint(products_bp)
if __name__ == '__main__':
app.run(debug=True)
# Routes available:
# GET /api/users/
# GET /api/users/<id>
# POST /api/users/
# GET /api/products/
# GET /api/products/<id>Route Rules and URL Map
Inspect registered routes in your app:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Home'
@app.route('/about')
def about():
return 'About'
# Print all routes
with app.app_context():
for rule in app.url_map.iter_rules():
methods = ','.join(rule.methods)
print(f'{rule.endpoint:30s} {methods:30s} {rule}')
# Output:
# index GET,HEAD,OPTIONS /
# about GET,HEAD,OPTIONS /about
# static GET,HEAD,OPTIONS /static/<path:filename>Trailing Slash Behavior
Flask handles trailing slashes differently than some frameworks:
from flask import Flask
app = Flask(__name__)
# With trailing slash — redirects /projects to /projects/
@app.route('/projects/')
def projects():
return 'Projects list'
# Without trailing slash — /about/ returns 404
@app.route('/about')
def about():
return 'About page'
# Strict slashes (disable redirect)
@app.route('/api/users', strict_slashes=False)
def api_users():
return 'Users API' # Matches both /api/users and /api/users/Practice Exercises
Exercise 1: Blog API
Build a complete blog API with:
GET /posts— list all posts with pagination (?page=1&per_page=5)GET /posts/<int:id>— get a single postPOST /posts— create a postPUT /posts/<int:id>— update a postDELETE /posts/<int:id>— delete a postGET /posts/search?q=<term>— search posts
Exercise 2: URL Building
Create an app with 5 different routes and a "sitemap" route at /sitemap that uses url_for to return all available URLs as JSON.
Exercise 3: Blueprint Organization
Refactor the blog API into blueprints:
auth_bp— authentication routesposts_bp— post CRUD routescomments_bp— comment routes
Summary
In this lesson, you learned:
- ✅ Basic and dynamic routing with URL parameters
- ✅ URL converters (string, int, float, path, uuid)
- ✅ Creating custom URL converters
- ✅ Handling different HTTP methods (GET, POST, PUT, DELETE)
- ✅ RESTful route design patterns
- ✅ URL building with
url_for() - ✅ Redirects (301 and 302)
- ✅ Working with the request object
- ✅ Organizing routes with Blueprints
*Next Lesson: Flask Templates →*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Flask Routing.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, web, development, flask
Related Python Master Course Topics