Routing in Flask is the process of mapping URLs to Python functions that handle incoming requests.
It is one of the core concepts used to build web pages and APIs in Flask applications.
What is Routing?
Routing determines what code should run when a specific URL is accessed in a Flask application.
Each route is linked to a function that returns a response to the client.
Basic Route in Flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Home Page'The @app.route('/') decorator maps the root URL to the home function.
Multiple Routes
Flask allows you to define multiple routes for different pages or API endpoints.
@app.route('/about')
def about():
return 'About Page'
@app.route('/contact')
def contact():
return 'Contact Page'Dynamic Routes
Dynamic routes allow you to pass variables through the URL.
This is useful for accessing specific resources like user profiles or product details.
@app.route('/user/<name>')
def user(name):
return f'Hello {name}'Integer Parameters in Routes
Flask also allows type-specific routing such as integers.
@app.route('/post/<int:id>')
def post(id):
return f'Post ID: {id}'HTTP Methods in Routing
Routes can handle different HTTP methods like GET and POST.
By default, Flask routes only accept GET requests.
@app.route('/submit', methods=['GET', 'POST'])
def submit():
return 'Form Submitted'URL Building
Flask provides a way to generate URLs dynamically using the url_for function.
from flask import url_for
url_for('home')Why URL Building is Useful
It helps avoid hardcoding URLs, making applications easier to maintain.
If a route changes, url_for automatically updates it.
Handling Query Parameters
Query parameters are used to pass data in the URL after a question mark.
from flask import request
@app.route('/search')
def search():
query = request.args.get('q')
return f'Searching for {query}'Route Organization
In larger applications, routes are organized using Blueprints.
Blueprints help split applications into modular components.
Blueprint Example
from flask import Blueprint
user_bp = Blueprint('user', __name__)
@user_bp.route('/profile')
def profile():
return 'User Profile'Common Beginner Mistakes
Beginners often forget to use methods parameter for POST requests.
Another mistake is hardcoding URLs instead of using url_for.
Best Practices
Use dynamic routes for reusable endpoints and keep route functions simple.
Organize large applications using Blueprints for better structure.
Real-World Importance
Routing is essential in building APIs, web applications, and backend services using Flask.
It defines how users interact with backend systems through URLs.
Summary
Flask routing maps URLs to Python functions that handle requests.
Understanding routing is essential for building structured Flask applications.